

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/fluid.png">
  <link rel="icon" href="/blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Solace">
  <meta name="keywords" content="">
  
    <meta name="description" content="禹神yyds">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue3学习笔记">
<meta property="og:url" content="https://isolace.gitee.io/blog/2024/03/26/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="Solace的博客">
<meta property="og:description" content="禹神yyds">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://isolace.gitee.io/blog/post_img/index_img/vue3yu.jpg">
<meta property="article:published_time" content="2024-03-26T12:52:30.000Z">
<meta property="article:modified_time" content="2024-03-26T13:35:04.194Z">
<meta property="article:author" content="Solace">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="vue">
<meta property="article:tag" content="vue3">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://isolace.gitee.io/blog/post_img/index_img/vue3yu.jpg">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>Vue3学习笔记 - Solace的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"isolace.gitee.io","root":"/blog/","version":"1.9.5-a","typing":{"enable":true,"typeSpeed":60,"cursorChar":"|","loop":false,"scope":["home"]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/blog/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
  

  

  
    <!-- Google tag (gtag.js) -->
    <script async>
      if (!Fluid.ctx.dnt) {
        Fluid.utils.createScript("https://www.googletagmanager.com/gtag/js?id=", function() {
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '');
        });
      }
    </script>
  

  

  

  

  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blog/">
      <strong>Solace&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle">Vue3学习笔记</span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        Solace
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2024-03-26 20:52" pubdate>
          2024年3月26日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          51k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          429 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">Vue3学习笔记</h1>
            
            
              <div class="markdown-body">
                
                <p><a href='https://isolace.gitee.io/vue3atguigu'>点我跳转查看</a></p>
<h1 id="1-Vue3简介"><a href="#1-Vue3简介" class="headerlink" title="1. Vue3简介"></a>1. Vue3简介</h1><h2 id="1-2-【-源码的升级】"><a href="#1-2-【-源码的升级】" class="headerlink" title="1.2.【 源码的升级】"></a>1.2.【 源码的升级】</h2><ul>
<li><p>使用<code>Proxy</code>代替<code>defineProperty</code>实现响应式。</p>
</li>
<li><p>重写虚拟<code>DOM</code>的实现和<code>Tree-Shaking</code>。</p>
</li>
</ul>
<h2 id="1-3-【拥抱TypeScript】"><a href="#1-3-【拥抱TypeScript】" class="headerlink" title="1.3. 【拥抱TypeScript】"></a>1.3. 【拥抱TypeScript】</h2><ul>
<li><code>Vue3</code>可以更好的支持<code>TypeScript</code>。</li>
</ul>
<h2 id="1-4-【新的特性】"><a href="#1-4-【新的特性】" class="headerlink" title="1.4. 【新的特性】"></a>1.4. 【新的特性】</h2><ol>
<li><p><code>Composition API</code>（组合<code>API</code>）：</p>
<ul>
<li><p><code>setup</code></p>
</li>
<li><p><code>ref</code>与<code>reactive</code></p>
</li>
<li><p><code>computed</code>与<code>watch</code></p>
<p>……</p>
</li>
</ul>
</li>
<li><p>新的内置组件：</p>
<ul>
<li><p><code>Fragment</code></p>
</li>
<li><p><code>Teleport</code></p>
</li>
<li><p><code>Suspense</code></p>
<p>……</p>
</li>
</ul>
</li>
<li><p>其他改变：</p>
<ul>
<li><p>新的生命周期钩子</p>
</li>
<li><p><code>data</code> 选项应始终被声明为一个函数</p>
</li>
<li><p>移除<code>keyCode</code>支持作为<code> v-on</code> 的修饰符</p>
<p>……</p>
</li>
</ul>
</li>
</ol>
<h1 id="2-创建Vue3工程"><a href="#2-创建Vue3工程" class="headerlink" title="2. 创建Vue3工程"></a>2. 创建Vue3工程</h1><h2 id="2-1-【基于-vue-cli-创建】"><a href="#2-1-【基于-vue-cli-创建】" class="headerlink" title="2.1. 【基于 vue-cli 创建】"></a>2.1. 【基于 vue-cli 创建】</h2><p>点击查看<a target="_blank" rel="noopener" href="https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create">官方文档</a></p>
<blockquote>
<p>备注：目前<code>vue-cli</code>已处于维护模式，官方推荐基于 <code>Vite</code> 创建项目。</p>
</blockquote>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs powershell"><span class="hljs-comment">## 查看@vue/cli版本，确保@vue/cli版本在4.5.0以上</span><br>vue <span class="hljs-literal">--version</span><br><br><span class="hljs-comment">## 安装或者升级你的@vue/cli </span><br>npm install <span class="hljs-literal">-g</span> @vue/<span class="hljs-built_in">cli</span><br><br><span class="hljs-comment">## 执行创建命令</span><br>vue create vue_test<br><br><span class="hljs-comment">##  随后选择3.x</span><br><span class="hljs-comment">##  Choose a version of Vue.js that you want to start the project with (Use arrow keys)</span><br><span class="hljs-comment">##  &gt; 3.x</span><br><span class="hljs-comment">##    2.x</span><br><br><span class="hljs-comment">## 启动</span><br><span class="hljs-built_in">cd</span> vue_test<br>npm run serve<br></code></pre></td></tr></table></figure>

<hr>
<h2 id="2-2-【基于-vite-创建】-推荐"><a href="#2-2-【基于-vite-创建】-推荐" class="headerlink" title="2.2. 【基于 vite 创建】(推荐)"></a>2.2. 【基于 vite 创建】(推荐)</h2><p><code>vite</code> 是新一代前端构建工具，官网地址：<a target="_blank" rel="noopener" href="https://vitejs.cn/">https://vitejs.cn</a>，<code>vite</code>的优势如下：</p>
<ul>
<li>轻量快速的热重载（<code>HMR</code>），能实现极速的服务启动。</li>
<li>对 <code>TypeScript</code>、<code>JSX</code>、<code>CSS</code> 等支持开箱即用。</li>
<li>真正的按需编译，不再等待整个应用编译完成。</li>
<li><code>webpack</code>构建 与 <code>vite</code>构建对比图如下：<br><img src="../../../../post_img/0326/Vue3learning/1683167182037-71c78210-8217-4e7d-9a83-e463035efbbe.png" srcset="/blog/img/loading.gif" lazyload alt="webpack构建" title="webpack构建" style="zoom:20%;box-shadow:0 0 10px black" />	<img src="../../../../post_img/0326/Vue3learning/1683167204081-582dc237-72bc-499e-9589-2cdfd452e62f.png" srcset="/blog/img/loading.gif" lazyload alt="vite构建" title="vite构建" style="zoom: 20%;box-shadow:0 0 10px black" /></li>
</ul>
<ul>
<li>具体操作如下（点击查看<a target="_blank" rel="noopener" href="https://cn.vuejs.org/guide/quick-start.html#creating-a-vue-application">官方文档</a>）</li>
</ul>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs powershell"><span class="hljs-comment">## 1.创建命令</span><br>npm create vue@latest<br><br><span class="hljs-comment">## 2.具体配置</span><br><span class="hljs-comment">## 配置项目名称</span><br>√ Project name: vue3_test<br><span class="hljs-comment">## 是否添加TypeScript支持</span><br>√ Add TypeScript?  Yes<br><span class="hljs-comment">## 是否添加JSX支持</span><br>√ Add JSX Support?  No<br><span class="hljs-comment">## 是否添加路由环境</span><br>√ Add Vue Router <span class="hljs-keyword">for</span> Single Page Application development?  No<br><span class="hljs-comment">## 是否添加pinia环境</span><br>√ Add Pinia <span class="hljs-keyword">for</span> state management?  No<br><span class="hljs-comment">## 是否添加单元测试</span><br>√ Add Vitest <span class="hljs-keyword">for</span> Unit Testing?  No<br><span class="hljs-comment">## 是否添加端到端测试方案</span><br>√ Add an <span class="hljs-keyword">End</span><span class="hljs-literal">-to-End</span> Testing Solution? » No<br><span class="hljs-comment">## 是否添加ESLint语法检查</span><br>√ Add ESLint <span class="hljs-keyword">for</span> code quality?  Yes<br><span class="hljs-comment">## 是否添加Prettiert代码格式化</span><br>√ Add Prettier <span class="hljs-keyword">for</span> code formatting?  No<br></code></pre></td></tr></table></figure>

<p>自己动手编写一个App组件</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;app&quot;&gt;<br>    &lt;h1&gt;你好啊！&lt;/h1&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot;&gt;<br>  export default &#123;<br>    name:&#x27;App&#x27; //组件名<br>  &#125;<br>&lt;/script&gt;<br><br>&lt;style&gt;<br>  .app &#123;<br>    background-color: #ddd;<br>    box-shadow: 0 0 10px;<br>    border-radius: 10px;<br>    padding: 20px;<br>  &#125;<br>&lt;/style&gt;<br></code></pre></td></tr></table></figure>

<p>安装官方推荐的<code>vscode</code>插件：</p>
<img src="../../../../post_img/0326/Vue3learning/volar.png" srcset="/blog/img/loading.gif" lazyload alt="Snipaste_2023-10-08_20-46-34" style="zoom:50%;" /> 

<img src="../../../../post_img/0326/Vue3learning/image-20231218085906380.png" srcset="/blog/img/loading.gif" lazyload alt="image-20231218085906380" style="zoom:42%;" /> 

<p>总结：</p>
<ul>
<li><code>Vite</code> 项目中，<code>index.html</code> 是项目的入口文件，在项目最外层。</li>
<li>加载<code>index.html</code>后，<code>Vite</code> 解析 <code>&lt;script type=&quot;module&quot; src=&quot;xxx&quot;&gt;</code> 指向的<code>JavaScript</code>。</li>
<li><code>Vue3</code>**中是通过 **<code>createApp</code> 函数创建一个应用实例。</li>
</ul>
<h2 id="2-3-【一个简单的效果】"><a href="#2-3-【一个简单的效果】" class="headerlink" title="2.3. 【一个简单的效果】"></a>2.3. 【一个简单的效果】</h2><p><code>Vue3</code>向下兼容<code>Vue2</code>语法，且<code>Vue3</code>中的模板中可以没有根标签</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h2&gt;姓名：&#123;&#123;name&#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;年龄：&#123;&#123;age&#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeName&quot;&gt;修改名字&lt;/button&gt;<br>    &lt;button @click=&quot;changeAge&quot;&gt;年龄+1&lt;/button&gt;<br>    &lt;button @click=&quot;showTel&quot;&gt;点我查看联系方式&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot;&gt;<br>  export default &#123;<br>    name:&#x27;App&#x27;,<br>    data() &#123;<br>      return &#123;<br>        name:&#x27;张三&#x27;,<br>        age:18,<br>        tel:&#x27;13888888888&#x27;<br>      &#125;<br>    &#125;,<br>    methods:&#123;<br>      changeName()&#123;<br>        this.name = &#x27;zhang-san&#x27;<br>      &#125;,<br>      changeAge()&#123;<br>        this.age += 1<br>      &#125;,<br>      showTel()&#123;<br>        alert(this.tel)<br>      &#125;<br>    &#125;,<br>  &#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>


<h1 id="3-Vue3核心语法"><a href="#3-Vue3核心语法" class="headerlink" title="3. Vue3核心语法"></a>3. Vue3核心语法</h1><h2 id="3-1-【OptionsAPI-与-CompositionAPI】"><a href="#3-1-【OptionsAPI-与-CompositionAPI】" class="headerlink" title="3.1.  【OptionsAPI 与 CompositionAPI】"></a>3.1.  【OptionsAPI 与 CompositionAPI】</h2><ul>
<li><code>Vue2</code>的<code>API</code>设计是<code>Options</code>（配置）风格的。</li>
<li><code>Vue3</code>的<code>API</code>设计是<code>Composition</code>（组合）风格的。</li>
</ul>
<h3 id="Options-API-的弊端"><a href="#Options-API-的弊端" class="headerlink" title="Options API 的弊端"></a>Options API 的弊端</h3><p><code>Options</code>类型的 <code>API</code>，数据、方法、计算属性等，是分散在：<code>data</code>、<code>methods</code>、<code>computed</code>中的，若想新增或者修改一个需求，就需要分别修改：<code>data</code>、<code>methods</code>、<code>computed</code>，不便于维护和复用。</p>
<p><img src="../../../../post_img/0326/Vue3learning/1696662197101-55d2b251-f6e5-47f4-b3f1-d8531bbf9279.gif" srcset="/blog/img/loading.gif" lazyload alt="1.gif" style="zoom:70%;border-radius:20px" /><img src="../../../../post_img/0326/Vue3learning/1696662200734-1bad8249-d7a2-423e-a3c3-ab4c110628be.gif" srcset="/blog/img/loading.gif" lazyload alt="2.gif" style="zoom:70%;border-radius:20px" /></p>
<h3 id="Composition-API-的优势"><a href="#Composition-API-的优势" class="headerlink" title="Composition API 的优势"></a>Composition API 的优势</h3><p>可以用函数的方式，更加优雅的组织代码，让相关功能的代码更加有序的组织在一起。</p>
<p><img src="../../../../post_img/0326/Vue3learning/1696662249851-db6403a1-acb5-481a-88e0-e1e34d2ef53a.gif" srcset="/blog/img/loading.gif" lazyload alt="3.gif" style="height:300px;border-radius:10px"  /><img src="../../../../post_img/0326/Vue3learning/1696662256560-7239b9f9-a770-43c1-9386-6cc12ef1e9c0.gif" srcset="/blog/img/loading.gif" lazyload alt="4.gif" style="height:300px;border-radius:10px"  /></p>
<blockquote>
<p>说明：以上四张动图原创作者：大帅老猿</p>
</blockquote>
<h2 id="3-2-【拉开序幕的-setup】"><a href="#3-2-【拉开序幕的-setup】" class="headerlink" title="3.2. 【拉开序幕的 setup】"></a>3.2. 【拉开序幕的 setup】</h2><h3 id="setup-概述"><a href="#setup-概述" class="headerlink" title="setup 概述"></a>setup 概述</h3><p><code>setup</code>是<code>Vue3</code>中一个新的配置项，值是一个函数，它是 <code>Composition API</code> <strong>“表演的舞台</strong>_<strong>”</strong>_，组件中所用到的：数据、方法、计算属性、监视……等等，均配置在<code>setup</code>中。</p>
<p>特点如下：</p>
<ul>
<li><code>setup</code>函数返回的对象中的内容，可直接在模板中使用。</li>
<li><code>setup</code>中访问<code>this</code>是<code>undefined</code>。</li>
<li><code>setup</code>函数会在<code>beforeCreate</code>之前调用，它是“领先”所有钩子执行的。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h2&gt;姓名：&#123;&#123;name&#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;年龄：&#123;&#123;age&#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeName&quot;&gt;修改名字&lt;/button&gt;<br>    &lt;button @click=&quot;changeAge&quot;&gt;年龄+1&lt;/button&gt;<br>    &lt;button @click=&quot;showTel&quot;&gt;点我查看联系方式&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot;&gt;<br>  export default &#123;<br>    name:&#x27;Person&#x27;,<br>    setup()&#123;<br>      // 数据，原来写在data中（注意：此时的name、age、tel数据都不是响应式数据）<br>      let name = &#x27;张三&#x27;<br>      let age = 18<br>      let tel = &#x27;13888888888&#x27;<br><br>      // 方法，原来写在methods中<br>      function changeName()&#123;<br>        name = &#x27;zhang-san&#x27; //注意：此时这么修改name页面是不变化的<br>        console.log(name)<br>      &#125;<br>      function changeAge()&#123;<br>        age += 1 //注意：此时这么修改age页面是不变化的<br>        console.log(age)<br>      &#125;<br>      function showTel()&#123;<br>        alert(tel)<br>      &#125;<br><br>      // 返回一个对象，对象中的内容，模板中可以直接使用<br>      return &#123;name,age,tel,changeName,changeAge,showTel&#125;<br>    &#125;<br>  &#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h3 id="setup-的返回值"><a href="#setup-的返回值" class="headerlink" title="setup 的返回值"></a>setup 的返回值</h3><ul>
<li>若返回一个<strong>对象</strong>：则对象中的：属性、方法等，在模板中均可以直接使用<strong>（重点关注）。</strong></li>
<li>若返回一个<strong>函数</strong>：则可以自定义渲染内容，代码如下：</li>
</ul>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs jsx"><span class="hljs-title function_">setup</span>(<span class="hljs-params"></span>)&#123;<br>  <span class="hljs-keyword">return</span> <span class="hljs-function">()=&gt;</span> <span class="hljs-string">&#x27;你好啊！&#x27;</span><br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="setup-与-Options-API-的关系"><a href="#setup-与-Options-API-的关系" class="headerlink" title="setup 与 Options API 的关系"></a>setup 与 Options API 的关系</h3><ul>
<li><code>Vue2</code> 的配置（<code>data</code>、<code>methos</code>……）中<strong>可以访问到</strong> <code>setup</code>中的属性、方法。</li>
<li>但在<code>setup</code>中<strong>不能访问到</strong><code>Vue2</code>的配置（<code>data</code>、<code>methos</code>……）。</li>
<li>如果与<code>Vue2</code>冲突，则<code>setup</code>优先。</li>
</ul>
<h3 id="setup-语法糖"><a href="#setup-语法糖" class="headerlink" title="setup 语法糖"></a>setup 语法糖</h3><p><code>setup</code>函数有一个语法糖，这个语法糖，可以让我们把<code>setup</code>独立出去，代码如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h2&gt;姓名：&#123;&#123;name&#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;年龄：&#123;&#123;age&#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changName&quot;&gt;修改名字&lt;/button&gt;<br>    &lt;button @click=&quot;changAge&quot;&gt;年龄+1&lt;/button&gt;<br>    &lt;button @click=&quot;showTel&quot;&gt;点我查看联系方式&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot;&gt;<br>  export default &#123;<br>    name:&#x27;Person&#x27;,<br>  &#125;<br>&lt;/script&gt;<br><br>&lt;!-- 下面的写法是setup语法糖 --&gt;<br>&lt;script setup lang=&quot;ts&quot;&gt;<br>  console.log(this) //undefined<br>  <br>  // 数据（注意：此时的name、age、tel都不是响应式数据）<br>  let name = &#x27;张三&#x27;<br>  let age = 18<br>  let tel = &#x27;13888888888&#x27;<br><br>  // 方法<br>  function changName()&#123;<br>    name = &#x27;李四&#x27;//注意：此时这么修改name页面是不变化的<br>  &#125;<br>  function changAge()&#123;<br>    console.log(age)<br>    age += 1 //注意：此时这么修改age页面是不变化的<br>  &#125;<br>  function showTel()&#123;<br>    alert(tel)<br>  &#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>扩展：上述代码，还需要编写一个不写<code>setup</code>的<code>script</code>标签，去指定组件名字，比较麻烦，我们可以借助<code>vite</code>中的插件简化</p>
<ol>
<li>第一步：<code>npm i vite-plugin-vue-setup-extend -D</code></li>
<li>第二步：<code>vite.config.ts</code></li>
</ol>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs jsx"><span class="hljs-keyword">import</span> &#123; defineConfig &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vite&#x27;</span><br><span class="hljs-keyword">import</span> <span class="hljs-title class_">VueSetupExtend</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vite-plugin-vue-setup-extend&#x27;</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title function_">defineConfig</span>(&#123;<br>  <span class="hljs-attr">plugins</span>: [ <span class="hljs-title class_">VueSetupExtend</span>() ]<br>&#125;)<br></code></pre></td></tr></table></figure>

<ol start="3">
<li>第三步：<code>&lt;script setup lang=&quot;ts&quot; name=&quot;Person&quot;&gt;</code></li>
</ol>
<h2 id="3-3-【ref-创建：基本类型的响应式数据】"><a href="#3-3-【ref-创建：基本类型的响应式数据】" class="headerlink" title="3.3. 【ref 创建：基本类型的响应式数据】"></a>3.3. 【ref 创建：基本类型的响应式数据】</h2><ul>
<li><strong>作用：</strong>定义响应式变量。</li>
<li><strong>语法：</strong><code>let xxx = ref(初始值)</code>。</li>
<li><strong>返回值：</strong>一个<code>RefImpl</code>的实例对象，简称<code>ref对象</code>或<code>ref</code>，<code>ref</code>对象的<code>value</code><strong>属性是响应式的</strong>。</li>
<li><strong>注意点：</strong><ul>
<li><code>JS</code>中操作数据需要：<code>xxx.value</code>，但模板中不需要<code>.value</code>，直接使用即可。</li>
<li>对于<code>let name = ref(&#39;张三&#39;)</code>来说，<code>name</code>不是响应式的，<code>name.value</code>是响应式的。</li>
</ul>
</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h2&gt;姓名：&#123;&#123;name&#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;年龄：&#123;&#123;age&#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeName&quot;&gt;修改名字&lt;/button&gt;<br>    &lt;button @click=&quot;changeAge&quot;&gt;年龄+1&lt;/button&gt;<br>    &lt;button @click=&quot;showTel&quot;&gt;点我查看联系方式&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;Person&quot;&gt;<br>  import &#123;ref&#125; from &#x27;vue&#x27;<br>  // name和age是一个RefImpl的实例对象，简称ref对象，它们的value属性是响应式的。<br>  let name = ref(&#x27;张三&#x27;)<br>  let age = ref(18)<br>  // tel就是一个普通的字符串，不是响应式的<br>  let tel = &#x27;13888888888&#x27;<br><br>  function changeName()&#123;<br>    // JS中操作ref对象时候需要.value<br>    name.value = &#x27;李四&#x27;<br>    console.log(name.value)<br><br>    // 注意：name不是响应式的，name.value是响应式的，所以如下代码并不会引起页面的更新。<br>    // name = ref(&#x27;zhang-san&#x27;)<br>  &#125;<br>  function changeAge()&#123;<br>    // JS中操作ref对象时候需要.value<br>    age.value += 1 <br>    console.log(age.value)<br>  &#125;<br>  function showTel()&#123;<br>    alert(tel)<br>  &#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="3-4-【reactive-创建：对象类型的响应式数据】"><a href="#3-4-【reactive-创建：对象类型的响应式数据】" class="headerlink" title="3.4. 【reactive 创建：对象类型的响应式数据】"></a>3.4. 【reactive 创建：对象类型的响应式数据】</h2><ul>
<li><strong>作用：</strong>定义一个<strong>响应式对象</strong>（基本类型不要用它，要用<code>ref</code>，否则报错）</li>
<li><strong>语法：</strong><code>let 响应式对象= reactive(源对象)</code>。</li>
<li><strong>返回值：</strong>一个<code>Proxy</code>的实例对象，简称：响应式对象。</li>
<li><strong>注意点：</strong><code>reactive</code>定义的响应式数据是“深层次”的。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h2&gt;汽车信息：一台&#123;&#123; car.brand &#125;&#125;汽车，价值&#123;&#123; car.price &#125;&#125;万&lt;/h2&gt;<br>    &lt;h2&gt;游戏列表：&lt;/h2&gt;<br>    &lt;ul&gt;<br>      &lt;li v-for=&quot;g in games&quot; :key=&quot;g.id&quot;&gt;&#123;&#123; g.name &#125;&#125;&lt;/li&gt;<br>    &lt;/ul&gt;<br>    &lt;h2&gt;测试：&#123;&#123;obj.a.b.c.d&#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeCarPrice&quot;&gt;修改汽车价格&lt;/button&gt;<br>    &lt;button @click=&quot;changeFirstGame&quot;&gt;修改第一游戏&lt;/button&gt;<br>    &lt;button @click=&quot;test&quot;&gt;测试&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>import &#123; reactive &#125; from &#x27;vue&#x27;<br><br>// 数据<br>let car = reactive(&#123; brand: &#x27;奔驰&#x27;, price: 100 &#125;)<br>let games = reactive([<br>  &#123; id: &#x27;ahsgdyfa01&#x27;, name: &#x27;英雄联盟&#x27; &#125;,<br>  &#123; id: &#x27;ahsgdyfa02&#x27;, name: &#x27;王者荣耀&#x27; &#125;,<br>  &#123; id: &#x27;ahsgdyfa03&#x27;, name: &#x27;原神&#x27; &#125;<br>])<br>let obj = reactive(&#123;<br>  a:&#123;<br>    b:&#123;<br>      c:&#123;<br>        d:666<br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;)<br><br>function changeCarPrice() &#123;<br>  car.price += 10<br>&#125;<br>function changeFirstGame() &#123;<br>  games[0].name = &#x27;流星蝴蝶剑&#x27;<br>&#125;<br>function test()&#123;<br>  obj.a.b.c.d = 999<br>&#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="3-5-【ref-创建：对象类型的响应式数据】"><a href="#3-5-【ref-创建：对象类型的响应式数据】" class="headerlink" title="3.5. 【ref 创建：对象类型的响应式数据】"></a>3.5. 【ref 创建：对象类型的响应式数据】</h2><ul>
<li>其实<code>ref</code>接收的数据可以是：<strong>基本类型</strong>、<strong>对象类型</strong>。</li>
<li>若<code>ref</code>接收的是对象类型，内部其实也是调用了<code>reactive</code>函数。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h2&gt;汽车信息：一台&#123;&#123; car.brand &#125;&#125;汽车，价值&#123;&#123; car.price &#125;&#125;万&lt;/h2&gt;<br>    &lt;h2&gt;游戏列表：&lt;/h2&gt;<br>    &lt;ul&gt;<br>      &lt;li v-for=&quot;g in games&quot; :key=&quot;g.id&quot;&gt;&#123;&#123; g.name &#125;&#125;&lt;/li&gt;<br>    &lt;/ul&gt;<br>    &lt;h2&gt;测试：&#123;&#123;obj.a.b.c.d&#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeCarPrice&quot;&gt;修改汽车价格&lt;/button&gt;<br>    &lt;button @click=&quot;changeFirstGame&quot;&gt;修改第一游戏&lt;/button&gt;<br>    &lt;button @click=&quot;test&quot;&gt;测试&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>import &#123; ref &#125; from &#x27;vue&#x27;<br><br>// 数据<br>let car = ref(&#123; brand: &#x27;奔驰&#x27;, price: 100 &#125;)<br>let games = ref([<br>  &#123; id: &#x27;ahsgdyfa01&#x27;, name: &#x27;英雄联盟&#x27; &#125;,<br>  &#123; id: &#x27;ahsgdyfa02&#x27;, name: &#x27;王者荣耀&#x27; &#125;,<br>  &#123; id: &#x27;ahsgdyfa03&#x27;, name: &#x27;原神&#x27; &#125;<br>])<br>let obj = ref(&#123;<br>  a:&#123;<br>    b:&#123;<br>      c:&#123;<br>        d:666<br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;)<br><br>console.log(car)<br><br>function changeCarPrice() &#123;<br>  car.value.price += 10<br>&#125;<br>function changeFirstGame() &#123;<br>  games.value[0].name = &#x27;流星蝴蝶剑&#x27;<br>&#125;<br>function test()&#123;<br>  obj.value.a.b.c.d = 999<br>&#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="3-6-【ref-对比-reactive】"><a href="#3-6-【ref-对比-reactive】" class="headerlink" title="3.6. 【ref 对比 reactive】"></a>3.6. 【ref 对比 reactive】</h2><p>宏观角度看：</p>
<blockquote>
<ol>
<li><p><code>ref</code>用来定义：<strong>基本类型数据</strong>、<strong>对象类型数据</strong>；</p>
</li>
<li><p><code>reactive</code>用来定义：<strong>对象类型数据</strong>。</p>
</li>
</ol>
</blockquote>
<ul>
<li>区别：</li>
</ul>
<blockquote>
<ol>
<li><p><code>ref</code>创建的变量必须使用<code>.value</code>（可以使用<code>volar</code>插件自动添加<code>.value</code>）。</p>
<img src="../../../../post_img/0326/Vue3learning/自动补充value.png" srcset="/blog/img/loading.gif" lazyload alt="自动补充value" style="zoom:50%;border-radius:20px" /> 
</li>
<li><p><code>reactive</code>重新分配一个新对象，会<strong>失去</strong>响应式（可以使用<code>Object.assign</code>去整体替换）。</p>
</li>
</ol>
</blockquote>
<ul>
<li>使用原则：</li>
</ul>
<blockquote>
<ol>
<li>若需要一个基本类型的响应式数据，必须使用<code>ref</code>。</li>
<li>若需要一个响应式对象，层级不深，<code>ref</code>、<code>reactive</code>都可以。</li>
<li>若需要一个响应式对象，且层级较深，推荐使用<code>reactive</code>。</li>
</ol>
</blockquote>
<h2 id="3-7-【toRefs-与-toRef】"><a href="#3-7-【toRefs-与-toRef】" class="headerlink" title="3.7. 【toRefs 与 toRef】"></a>3.7. 【toRefs 与 toRef】</h2><ul>
<li>作用：将一个响应式对象中的每一个属性，转换为<code>ref</code>对象。</li>
<li>备注：<code>toRefs</code>与<code>toRef</code>功能一致，但<code>toRefs</code>可以批量转换。</li>
<li>语法如下：</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h2&gt;姓名：&#123;&#123;person.name&#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;年龄：&#123;&#123;person.age&#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;性别：&#123;&#123;person.gender&#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeName&quot;&gt;修改名字&lt;/button&gt;<br>    &lt;button @click=&quot;changeAge&quot;&gt;修改年龄&lt;/button&gt;<br>    &lt;button @click=&quot;changeGender&quot;&gt;修改性别&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>  import &#123;ref,reactive,toRefs,toRef&#125; from &#x27;vue&#x27;<br><br>  // 数据<br>  let person = reactive(&#123;name:&#x27;张三&#x27;, age:18, gender:&#x27;男&#x27;&#125;)<br>	<br>  // 通过toRefs将person对象中的n个属性批量取出，且依然保持响应式的能力<br>  let &#123;name,gender&#125; =  toRefs(person)<br>	<br>  // 通过toRef将person对象中的gender属性取出，且依然保持响应式的能力<br>  let age = toRef(person,&#x27;age&#x27;)<br><br>  // 方法<br>  function changeName()&#123;<br>    name.value += &#x27;~&#x27;<br>  &#125;<br>  function changeAge()&#123;<br>    age.value += 1<br>  &#125;<br>  function changeGender()&#123;<br>    gender.value = &#x27;女&#x27;<br>  &#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="3-8-【computed】"><a href="#3-8-【computed】" class="headerlink" title="3.8. 【computed】"></a>3.8. 【computed】</h2><p>作用：根据已有数据计算出新数据（和<code>Vue2</code>中的<code>computed</code>作用一致）。</p>
<img src="../../../../post_img/0326/Vue3learning/computed.gif" srcset="/blog/img/loading.gif" lazyload style="zoom:20%;" />  

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    姓：&lt;input type=&quot;text&quot; v-model=&quot;firstName&quot;&gt; &lt;br&gt;<br>    名：&lt;input type=&quot;text&quot; v-model=&quot;lastName&quot;&gt; &lt;br&gt;<br>    全名：&lt;span&gt;&#123;&#123;fullName&#125;&#125;&lt;/span&gt; &lt;br&gt;<br>    &lt;button @click=&quot;changeFullName&quot;&gt;全名改为：li-si&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;App&quot;&gt;<br>  import &#123;ref,computed&#125; from &#x27;vue&#x27;<br><br>  let firstName = ref(&#x27;zhang&#x27;)<br>  let lastName = ref(&#x27;san&#x27;)<br><br>  // 计算属性——只读取，不修改<br>  /* let fullName = computed(()=&gt;&#123;<br>    return firstName.value + &#x27;-&#x27; + lastName.value<br>  &#125;) */<br><br><br>  // 计算属性——既读取又修改<br>  let fullName = computed(&#123;<br>    // 读取<br>    get()&#123;<br>      return firstName.value + &#x27;-&#x27; + lastName.value<br>    &#125;,<br>    // 修改<br>    set(val)&#123;<br>      console.log(&#x27;有人修改了fullName&#x27;,val)<br>      firstName.value = val.split(&#x27;-&#x27;)[0]<br>      lastName.value = val.split(&#x27;-&#x27;)[1]<br>    &#125;<br>  &#125;)<br><br>  function changeFullName()&#123;<br>    fullName.value = &#x27;li-si&#x27;<br>  &#125; <br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="3-9-【watch】"><a href="#3-9-【watch】" class="headerlink" title="3.9.【watch】"></a>3.9.【watch】</h2><ul>
<li>作用：监视数据的变化（和<code>Vue2</code>中的<code>watch</code>作用一致）</li>
<li>特点：<code>Vue3</code>中的<code>watch</code>只能监视以下<strong>四种数据</strong>：</li>
</ul>
<blockquote>
<ol>
<li><code>ref</code>定义的数据。</li>
<li><code>reactive</code>定义的数据。</li>
<li>函数返回一个值（<code>getter</code>函数）。</li>
<li>一个包含上述内容的数组。</li>
</ol>
</blockquote>
<p>我们在<code>Vue3</code>中使用<code>watch</code>的时候，通常会遇到以下几种情况：</p>
<h3 id="情况一"><a href="#情况一" class="headerlink" title="* 情况一"></a>* 情况一</h3><p>监视<code>ref</code>定义的【基本类型】数据：直接写数据名即可，监视的是其<code>value</code>值的改变。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h1&gt;情况一：监视【ref】定义的【基本类型】数据&lt;/h1&gt;<br>    &lt;h2&gt;当前求和为：&#123;&#123;sum&#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeSum&quot;&gt;点我sum+1&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>  import &#123;ref,watch&#125; from &#x27;vue&#x27;<br>  // 数据<br>  let sum = ref(0)<br>  // 方法<br>  function changeSum()&#123;<br>    sum.value += 1<br>  &#125;<br>  // 监视，情况一：监视【ref】定义的【基本类型】数据<br>  const stopWatch = watch(sum,(newValue,oldValue)=&gt;&#123;<br>    console.log(&#x27;sum变化了&#x27;,newValue,oldValue)<br>    if(newValue &gt;= 10)&#123;<br>      stopWatch()<br>    &#125;<br>  &#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h3 id="情况二"><a href="#情况二" class="headerlink" title="* 情况二"></a>* 情况二</h3><p>监视<code>ref</code>定义的【对象类型】数据：直接写数据名，监视的是对象的【地址值】，若想监视对象内部的数据，要手动开启深度监视。</p>
<blockquote>
<p>注意：</p>
<ul>
<li><p>若修改的是<code>ref</code>定义的对象中的属性，<code>newValue</code> 和 <code>oldValue</code> 都是新值，因为它们是同一个对象。</p>
</li>
<li><p>若修改整个<code>ref</code>定义的对象，<code>newValue</code> 是新值， <code>oldValue</code> 是旧值，因为不是同一个对象了。</p>
</li>
</ul>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h1&gt;情况二：监视【ref】定义的【对象类型】数据&lt;/h1&gt;<br>    &lt;h2&gt;姓名：&#123;&#123; person.name &#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;年龄：&#123;&#123; person.age &#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeName&quot;&gt;修改名字&lt;/button&gt;<br>    &lt;button @click=&quot;changeAge&quot;&gt;修改年龄&lt;/button&gt;<br>    &lt;button @click=&quot;changePerson&quot;&gt;修改整个人&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>  import &#123;ref,watch&#125; from &#x27;vue&#x27;<br>  // 数据<br>  let person = ref(&#123;<br>    name:&#x27;张三&#x27;,<br>    age:18<br>  &#125;)<br>  // 方法<br>  function changeName()&#123;<br>    person.value.name += &#x27;~&#x27;<br>  &#125;<br>  function changeAge()&#123;<br>    person.value.age += 1<br>  &#125;<br>  function changePerson()&#123;<br>    person.value = &#123;name:&#x27;李四&#x27;,age:90&#125;<br>  &#125;<br>  /* <br>    监视，情况一：监视【ref】定义的【对象类型】数据，监视的是对象的地址值，若想监视对象内部属性的变化，需要手动开启深度监视<br>    watch的第一个参数是：被监视的数据<br>    watch的第二个参数是：监视的回调<br>    watch的第三个参数是：配置对象（deep、immediate等等.....） <br>  */<br>  watch(person,(newValue,oldValue)=&gt;&#123;<br>    console.log(&#x27;person变化了&#x27;,newValue,oldValue)<br>  &#125;,&#123;deep:true&#125;)<br>  <br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h3 id="情况三"><a href="#情况三" class="headerlink" title="*  情况三"></a>*  情况三</h3><p>监视<code>reactive</code>定义的【对象类型】数据，且默认开启了深度监视。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h1&gt;情况三：监视【reactive】定义的【对象类型】数据&lt;/h1&gt;<br>    &lt;h2&gt;姓名：&#123;&#123; person.name &#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;年龄：&#123;&#123; person.age &#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeName&quot;&gt;修改名字&lt;/button&gt;<br>    &lt;button @click=&quot;changeAge&quot;&gt;修改年龄&lt;/button&gt;<br>    &lt;button @click=&quot;changePerson&quot;&gt;修改整个人&lt;/button&gt;<br>    &lt;hr&gt;<br>    &lt;h2&gt;测试：&#123;&#123;obj.a.b.c&#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;test&quot;&gt;修改obj.a.b.c&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>  import &#123;reactive,watch&#125; from &#x27;vue&#x27;<br>  // 数据<br>  let person = reactive(&#123;<br>    name:&#x27;张三&#x27;,<br>    age:18<br>  &#125;)<br>  let obj = reactive(&#123;<br>    a:&#123;<br>      b:&#123;<br>        c:666<br>      &#125;<br>    &#125;<br>  &#125;)<br>  // 方法<br>  function changeName()&#123;<br>    person.name += &#x27;~&#x27;<br>  &#125;<br>  function changeAge()&#123;<br>    person.age += 1<br>  &#125;<br>  function changePerson()&#123;<br>    Object.assign(person,&#123;name:&#x27;李四&#x27;,age:80&#125;)<br>  &#125;<br>  function test()&#123;<br>    obj.a.b.c = 888<br>  &#125;<br><br>  // 监视，情况三：监视【reactive】定义的【对象类型】数据，且默认是开启深度监视的<br>  watch(person,(newValue,oldValue)=&gt;&#123;<br>    console.log(&#x27;person变化了&#x27;,newValue,oldValue)<br>  &#125;)<br>  watch(obj,(newValue,oldValue)=&gt;&#123;<br>    console.log(&#x27;Obj变化了&#x27;,newValue,oldValue)<br>  &#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h3 id="情况四"><a href="#情况四" class="headerlink" title="* 情况四"></a>* 情况四</h3><p>监视<code>ref</code>或<code>reactive</code>定义的【对象类型】数据中的<strong>某个属性</strong>，注意点如下：</p>
<ol>
<li>若该属性值<strong>不是</strong>【对象类型】，需要写成函数形式。</li>
<li>若该属性值是<strong>依然</strong>是【对象类型】，可直接编，也可写成函数，建议写成函数。</li>
</ol>
<p>结论：监视的要是对象里的属性，那么最好写函数式，注意点：若是对象监视的是地址值，需要关注对象内部，需要手动开启深度监视。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h1&gt;情况四：监视【ref】或【reactive】定义的【对象类型】数据中的某个属性&lt;/h1&gt;<br>    &lt;h2&gt;姓名：&#123;&#123; person.name &#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;年龄：&#123;&#123; person.age &#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;汽车：&#123;&#123; person.car.c1 &#125;&#125;、&#123;&#123; person.car.c2 &#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeName&quot;&gt;修改名字&lt;/button&gt;<br>    &lt;button @click=&quot;changeAge&quot;&gt;修改年龄&lt;/button&gt;<br>    &lt;button @click=&quot;changeC1&quot;&gt;修改第一台车&lt;/button&gt;<br>    &lt;button @click=&quot;changeC2&quot;&gt;修改第二台车&lt;/button&gt;<br>    &lt;button @click=&quot;changeCar&quot;&gt;修改整个车&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>  import &#123;reactive,watch&#125; from &#x27;vue&#x27;<br><br>  // 数据<br>  let person = reactive(&#123;<br>    name:&#x27;张三&#x27;,<br>    age:18,<br>    car:&#123;<br>      c1:&#x27;奔驰&#x27;,<br>      c2:&#x27;宝马&#x27;<br>    &#125;<br>  &#125;)<br>  // 方法<br>  function changeName()&#123;<br>    person.name += &#x27;~&#x27;<br>  &#125;<br>  function changeAge()&#123;<br>    person.age += 1<br>  &#125;<br>  function changeC1()&#123;<br>    person.car.c1 = &#x27;奥迪&#x27;<br>  &#125;<br>  function changeC2()&#123;<br>    person.car.c2 = &#x27;大众&#x27;<br>  &#125;<br>  function changeCar()&#123;<br>    person.car = &#123;c1:&#x27;雅迪&#x27;,c2:&#x27;爱玛&#x27;&#125;<br>  &#125;<br><br>  // 监视，情况四：监视响应式对象中的某个属性，且该属性是基本类型的，要写成函数式<br>  /* watch(()=&gt; person.name,(newValue,oldValue)=&gt;&#123;<br>    console.log(&#x27;person.name变化了&#x27;,newValue,oldValue)<br>  &#125;) */<br><br>  // 监视，情况四：监视响应式对象中的某个属性，且该属性是对象类型的，可以直接写，也能写函数，更推荐写函数<br>  watch(()=&gt;person.car,(newValue,oldValue)=&gt;&#123;<br>    console.log(&#x27;person.car变化了&#x27;,newValue,oldValue)<br>  &#125;,&#123;deep:true&#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h3 id="情况五"><a href="#情况五" class="headerlink" title="* 情况五"></a>* 情况五</h3><p>监视上述的多个数据</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h1&gt;情况五：监视上述的多个数据&lt;/h1&gt;<br>    &lt;h2&gt;姓名：&#123;&#123; person.name &#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;年龄：&#123;&#123; person.age &#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;汽车：&#123;&#123; person.car.c1 &#125;&#125;、&#123;&#123; person.car.c2 &#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeName&quot;&gt;修改名字&lt;/button&gt;<br>    &lt;button @click=&quot;changeAge&quot;&gt;修改年龄&lt;/button&gt;<br>    &lt;button @click=&quot;changeC1&quot;&gt;修改第一台车&lt;/button&gt;<br>    &lt;button @click=&quot;changeC2&quot;&gt;修改第二台车&lt;/button&gt;<br>    &lt;button @click=&quot;changeCar&quot;&gt;修改整个车&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>  import &#123;reactive,watch&#125; from &#x27;vue&#x27;<br><br>  // 数据<br>  let person = reactive(&#123;<br>    name:&#x27;张三&#x27;,<br>    age:18,<br>    car:&#123;<br>      c1:&#x27;奔驰&#x27;,<br>      c2:&#x27;宝马&#x27;<br>    &#125;<br>  &#125;)<br>  // 方法<br>  function changeName()&#123;<br>    person.name += &#x27;~&#x27;<br>  &#125;<br>  function changeAge()&#123;<br>    person.age += 1<br>  &#125;<br>  function changeC1()&#123;<br>    person.car.c1 = &#x27;奥迪&#x27;<br>  &#125;<br>  function changeC2()&#123;<br>    person.car.c2 = &#x27;大众&#x27;<br>  &#125;<br>  function changeCar()&#123;<br>    person.car = &#123;c1:&#x27;雅迪&#x27;,c2:&#x27;爱玛&#x27;&#125;<br>  &#125;<br><br>  // 监视，情况五：监视上述的多个数据<br>  watch([()=&gt;person.name,person.car],(newValue,oldValue)=&gt;&#123;<br>    console.log(&#x27;person.car变化了&#x27;,newValue,oldValue)<br>  &#125;,&#123;deep:true&#125;)<br><br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="3-10-【watchEffect】"><a href="#3-10-【watchEffect】" class="headerlink" title="3.10. 【watchEffect】"></a>3.10. 【watchEffect】</h2><ul>
<li><p>官网：立即运行一个函数，同时响应式地追踪其依赖，并在依赖更改时重新执行该函数。</p>
</li>
<li><p><code>watch</code>对比<code>watchEffect</code></p>
<blockquote>
<ol>
<li><p>都能监听响应式数据的变化，不同的是监听数据变化的方式不同</p>
</li>
<li><p><code>watch</code>：要明确指出监视的数据</p>
</li>
<li><p><code>watchEffect</code>：不用明确指出监视的数据（函数中用到哪些属性，那就监视哪些属性）。</p>
</li>
</ol>
</blockquote>
</li>
<li><p>示例代码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h1&gt;需求：水温达到50℃，或水位达到20cm，则联系服务器&lt;/h1&gt;<br>    &lt;h2 id=&quot;demo&quot;&gt;水温：&#123;&#123;temp&#125;&#125;&lt;/h2&gt;<br>    &lt;h2&gt;水位：&#123;&#123;height&#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changePrice&quot;&gt;水温+1&lt;/button&gt;<br>    &lt;button @click=&quot;changeSum&quot;&gt;水位+10&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>  import &#123;ref,watch,watchEffect&#125; from &#x27;vue&#x27;<br>  // 数据<br>  let temp = ref(0)<br>  let height = ref(0)<br><br>  // 方法<br>  function changePrice()&#123;<br>    temp.value += 10<br>  &#125;<br>  function changeSum()&#123;<br>    height.value += 1<br>  &#125;<br><br>  // 用watch实现，需要明确的指出要监视：temp、height<br>  watch([temp,height],(value)=&gt;&#123;<br>    // 从value中获取最新的temp值、height值<br>    const [newTemp,newHeight] = value<br>    // 室温达到50℃，或水位达到20cm，立刻联系服务器<br>    if(newTemp &gt;= 50 || newHeight &gt;= 20)&#123;<br>      console.log(&#x27;联系服务器&#x27;)<br>    &#125;<br>  &#125;)<br><br>  // 用watchEffect实现，不用<br>  const stopWtach = watchEffect(()=&gt;&#123;<br>    // 室温达到50℃，或水位达到20cm，立刻联系服务器<br>    if(temp.value &gt;= 50 || height.value &gt;= 20)&#123;<br>      console.log(document.getElementById(&#x27;demo&#x27;)?.innerText)<br>      console.log(&#x27;联系服务器&#x27;)<br>    &#125;<br>    // 水温达到100，或水位达到50，取消监视<br>    if(temp.value === 100 || height.value === 50)&#123;<br>      console.log(&#x27;清理了&#x27;)<br>      stopWtach()<br>    &#125;<br>  &#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="3-11-【标签的-ref-属性】"><a href="#3-11-【标签的-ref-属性】" class="headerlink" title="3.11. 【标签的 ref 属性】"></a>3.11. 【标签的 ref 属性】</h2><p>作用：用于注册模板引用。</p>
<blockquote>
<ul>
<li><p>用在普通<code>DOM</code>标签上，获取的是<code>DOM</code>节点。</p>
</li>
<li><p>用在组件标签上，获取的是组件实例对象。</p>
</li>
</ul>
</blockquote>
<p>用在普通<code>DOM</code>标签上：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h1 ref=&quot;title1&quot;&gt;尚硅谷&lt;/h1&gt;<br>    &lt;h2 ref=&quot;title2&quot;&gt;前端&lt;/h2&gt;<br>    &lt;h3 ref=&quot;title3&quot;&gt;Vue&lt;/h3&gt;<br>    &lt;input type=&quot;text&quot; ref=&quot;inpt&quot;&gt; &lt;br&gt;&lt;br&gt;<br>    &lt;button @click=&quot;showLog&quot;&gt;点我打印内容&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>  import &#123;ref&#125; from &#x27;vue&#x27;<br>	<br>  let title1 = ref()<br>  let title2 = ref()<br>  let title3 = ref()<br><br>  function showLog()&#123;<br>    // 通过id获取元素<br>    const t1 = document.getElementById(&#x27;title1&#x27;)<br>    // 打印内容<br>    console.log((t1 as HTMLElement).innerText)<br>    console.log((&lt;HTMLElement&gt;t1).innerText)<br>    console.log(t1?.innerText)<br>    <br>		/************************************/<br>		<br>    // 通过ref获取元素<br>    console.log(title1.value)<br>    console.log(title2.value)<br>    console.log(title3.value)<br>  &#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>用在组件标签上：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;!-- 父组件App.vue --&gt;<br>&lt;template&gt;<br>  &lt;Person ref=&quot;ren&quot;/&gt;<br>  &lt;button @click=&quot;test&quot;&gt;测试&lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;App&quot;&gt;<br>  import Person from &#x27;./components/Person.vue&#x27;<br>  import &#123;ref&#125; from &#x27;vue&#x27;<br><br>  let ren = ref()<br><br>  function test()&#123;<br>    console.log(ren.value.name)<br>    console.log(ren.value.age)<br>  &#125;<br>&lt;/script&gt;<br><br><br>&lt;!-- 子组件Person.vue中要使用defineExpose暴露内容 --&gt;<br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>  import &#123;ref,defineExpose&#125; from &#x27;vue&#x27;<br>	// 数据<br>  let name = ref(&#x27;张三&#x27;)<br>  let age = ref(18)<br>  /****************************/<br>  /****************************/<br>  // 使用defineExpose将组件中的数据交给外部<br>  defineExpose(&#123;name,age&#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>



<h2 id="3-12-【props】"><a href="#3-12-【props】" class="headerlink" title="3.12. 【props】"></a>3.12. 【props】</h2><blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 定义一个接口，限制每个Person对象的格式</span><br><span class="hljs-keyword">export</span> interface <span class="hljs-title class_">PersonInter</span> &#123;<br><span class="hljs-attr">id</span>:string,<br><span class="hljs-attr">name</span>:string,<br> <span class="hljs-attr">age</span>:number<br>&#125;<br><br><span class="hljs-comment">// 定义一个自定义类型Persons</span><br><span class="hljs-keyword">export</span> type <span class="hljs-title class_">Persons</span> = <span class="hljs-title class_">Array</span>&lt;<span class="hljs-title class_">PersonInter</span>&gt;<br></code></pre></td></tr></table></figure>

<p><code>App.vue</code>中代码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;Person :list=&quot;persons&quot;/&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;App&quot;&gt;<br>import Person from &#x27;./components/Person.vue&#x27;<br>import &#123;reactive&#125; from &#x27;vue&#x27;<br> import &#123;type Persons&#125; from &#x27;./types&#x27;<br><br> let persons = reactive&lt;Persons&gt;([<br>  &#123;id:&#x27;e98219e12&#x27;,name:&#x27;张三&#x27;,age:18&#125;,<br>   &#123;id:&#x27;e98219e13&#x27;,name:&#x27;李四&#x27;,age:19&#125;,<br>    &#123;id:&#x27;e98219e14&#x27;,name:&#x27;王五&#x27;,age:20&#125;<br>  ])<br>&lt;/script&gt;<br><br></code></pre></td></tr></table></figure>

<p><code>Person.vue</code>中代码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs Vue">&lt;template&gt;<br>&lt;div class=&quot;person&quot;&gt;<br>&lt;ul&gt;<br>  &lt;li v-for=&quot;item in list&quot; :key=&quot;item.id&quot;&gt;<br>     &#123;&#123;item.name&#125;&#125;--&#123;&#123;item.age&#125;&#125;<br>   &lt;/li&gt;<br> &lt;/ul&gt;<br>&lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>import &#123;defineProps&#125; from &#x27;vue&#x27;<br>import &#123;type PersonInter&#125; from &#x27;@/types&#x27;<br><br>// 第一种写法：仅接收<br>// const props = defineProps([&#x27;list&#x27;])<br><br>// 第二种写法：接收+限制类型<br>// defineProps&lt;&#123;list:Persons&#125;&gt;()<br><br>// 第三种写法：接收+限制类型+指定默认值+限制必要性<br>let props = withDefaults(defineProps&lt;&#123;list?:Persons&#125;&gt;(),&#123;<br>  list:()=&gt;[&#123;id:&#x27;asdasg01&#x27;,name:&#x27;小猪佩奇&#x27;,age:18&#125;]<br>&#125;)<br>console.log(props)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>
</blockquote>
<h2 id="3-13-【生命周期】"><a href="#3-13-【生命周期】" class="headerlink" title="3.13. 【生命周期】"></a>3.13. 【生命周期】</h2><ul>
<li><p>概念：<code>Vue</code>组件实例在创建时要经历一系列的初始化步骤，在此过程中<code>Vue</code>会在合适的时机，调用特定的函数，从而让开发者有机会在特定阶段运行自己的代码，这些特定的函数统称为：生命周期钩子</p>
</li>
<li><p>规律：</p>
<blockquote>
<p>生命周期整体分为四个阶段，分别是：<strong>创建、挂载、更新、销毁</strong>，每个阶段都有两个钩子，一前一后。</p>
</blockquote>
</li>
<li><p><code>Vue2</code>的生命周期</p>
<blockquote>
<p>创建阶段：<code>beforeCreate</code>、<code>created</code></p>
<p>挂载阶段：<code>beforeMount</code>、<code>mounted</code></p>
<p>更新阶段：<code>beforeUpdate</code>、<code>updated</code></p>
<p>销毁阶段：<code>beforeDestroy</code>、<code>destroyed</code></p>
</blockquote>
</li>
<li><p><code>Vue3</code>的生命周期</p>
<blockquote>
<p>创建阶段：<code>setup</code></p>
<p>挂载阶段：<code>onBeforeMount</code>、<code>onMounted</code></p>
<p>更新阶段：<code>onBeforeUpdate</code>、<code>onUpdated</code></p>
<p>卸载阶段：<code>onBeforeUnmount</code>、<code>onUnmounted</code></p>
</blockquote>
</li>
<li><p>常用的钩子：<code>onMounted</code>(挂载完毕)、<code>onUpdated</code>(更新完毕)、<code>onBeforeUnmount</code>(卸载之前)</p>
</li>
<li><p>示例代码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;person&quot;&gt;<br>    &lt;h2&gt;当前求和为：&#123;&#123; sum &#125;&#125;&lt;/h2&gt;<br>    &lt;button @click=&quot;changeSum&quot;&gt;点我sum+1&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;!-- vue3写法 --&gt;<br>&lt;script lang=&quot;ts&quot; setup name=&quot;Person&quot;&gt;<br>  import &#123; <br>    ref, <br>    onBeforeMount, <br>    onMounted, <br>    onBeforeUpdate, <br>    onUpdated, <br>    onBeforeUnmount, <br>    onUnmounted <br>  &#125; from &#x27;vue&#x27;<br><br>  // 数据<br>  let sum = ref(0)<br>  // 方法<br>  function changeSum() &#123;<br>    sum.value += 1<br>  &#125;<br>  console.log(&#x27;setup&#x27;)<br>  // 生命周期钩子<br>  onBeforeMount(()=&gt;&#123;<br>    console.log(&#x27;挂载之前&#x27;)<br>  &#125;)<br>  onMounted(()=&gt;&#123;<br>    console.log(&#x27;挂载完毕&#x27;)<br>  &#125;)<br>  onBeforeUpdate(()=&gt;&#123;<br>    console.log(&#x27;更新之前&#x27;)<br>  &#125;)<br>  onUpdated(()=&gt;&#123;<br>    console.log(&#x27;更新完毕&#x27;)<br>  &#125;)<br>  onBeforeUnmount(()=&gt;&#123;<br>    console.log(&#x27;卸载之前&#x27;)<br>  &#125;)<br>  onUnmounted(()=&gt;&#123;<br>    console.log(&#x27;卸载完毕&#x27;)<br>  &#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="3-14-【自定义hook】"><a href="#3-14-【自定义hook】" class="headerlink" title="3.14. 【自定义hook】"></a>3.14. 【自定义hook】</h2><ul>
<li><p>什么是<code>hook</code>？—— 本质是一个函数，把<code>setup</code>函数中使用的<code>Composition API</code>进行了封装，类似于<code>vue2.x</code>中的<code>mixin</code>。</p>
</li>
<li><p>自定义<code>hook</code>的优势：复用代码, 让<code>setup</code>中的逻辑更清楚易懂。</p>
</li>
</ul>
<p>示例代码：</p>
<ul>
<li><p><code>useSum.ts</code>中内容如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123;ref,onMounted&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>  <span class="hljs-keyword">let</span> sum = <span class="hljs-title function_">ref</span>(<span class="hljs-number">0</span>)<br><br>  <span class="hljs-keyword">const</span> <span class="hljs-title function_">increment</span> = (<span class="hljs-params"></span>)=&gt;&#123;<br>    sum.<span class="hljs-property">value</span> += <span class="hljs-number">1</span><br>  &#125;<br>  <span class="hljs-keyword">const</span> <span class="hljs-title function_">decrement</span> = (<span class="hljs-params"></span>)=&gt;&#123;<br>    sum.<span class="hljs-property">value</span> -= <span class="hljs-number">1</span><br>  &#125;<br>  <span class="hljs-title function_">onMounted</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>    <span class="hljs-title function_">increment</span>()<br>  &#125;)<br><br>  <span class="hljs-comment">//向外部暴露数据</span><br>  <span class="hljs-keyword">return</span> &#123;sum,increment,decrement&#125;<br>&#125;		<br></code></pre></td></tr></table></figure>
</li>
<li><p><code>useDog.ts</code>中内容如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123;reactive,onMounted&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><span class="hljs-keyword">import</span> axios,&#123;<span class="hljs-title class_">AxiosError</span>&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;axios&#x27;</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>  <span class="hljs-keyword">let</span> dogList = reactive&lt;string[]&gt;([])<br><br>  <span class="hljs-comment">// 方法</span><br>  <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getDog</span>(<span class="hljs-params"></span>)&#123;<br>    <span class="hljs-keyword">try</span> &#123;<br>      <span class="hljs-comment">// 发请求</span><br>      <span class="hljs-keyword">let</span> &#123;data&#125; = <span class="hljs-keyword">await</span> axios.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;https://dog.ceo/api/breed/pembroke/images/random&#x27;</span>)<br>      <span class="hljs-comment">// 维护数据</span><br>      dogList.<span class="hljs-title function_">push</span>(data.<span class="hljs-property">message</span>)<br>    &#125; <span class="hljs-keyword">catch</span> (error) &#123;<br>      <span class="hljs-comment">// 处理错误</span><br>      <span class="hljs-keyword">const</span> err = &lt;<span class="hljs-title class_">AxiosError</span>&gt;error<br>      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err.<span class="hljs-property">message</span>)<br>    &#125;<br>  &#125;<br><br>  <span class="hljs-comment">// 挂载钩子</span><br>  <span class="hljs-title function_">onMounted</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>    <span class="hljs-title function_">getDog</span>()<br>  &#125;)<br>	<br>  <span class="hljs-comment">//向外部暴露数据</span><br>  <span class="hljs-keyword">return</span> &#123;dogList,getDog&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>组件中具体使用：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;h2&gt;当前求和为：&#123;&#123;sum&#125;&#125;&lt;/h2&gt;<br>  &lt;button @click=&quot;increment&quot;&gt;点我+1&lt;/button&gt;<br>  &lt;button @click=&quot;decrement&quot;&gt;点我-1&lt;/button&gt;<br>  &lt;hr&gt;<br>  &lt;img v-for=&quot;(u,index) in dogList.urlList&quot; :key=&quot;index&quot; :src=&quot;(u as string)&quot;&gt; <br>  &lt;span v-show=&quot;dogList.isLoading&quot;&gt;加载中......&lt;/span&gt;&lt;br&gt;<br>  &lt;button @click=&quot;getDog&quot;&gt;再来一只狗&lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot;&gt;<br>  import &#123;defineComponent&#125; from &#x27;vue&#x27;<br><br>  export default defineComponent(&#123;<br>    name:&#x27;App&#x27;,<br>  &#125;)<br>&lt;/script&gt;<br><br>&lt;script setup lang=&quot;ts&quot;&gt;<br>  import useSum from &#x27;./hooks/useSum&#x27;<br>  import useDog from &#x27;./hooks/useDog&#x27;<br>	<br>  let &#123;sum,increment,decrement&#125; = useSum()<br>  let &#123;dogList,getDog&#125; = useDog()<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure></li>
</ul>
<hr>
<h1 id="4-路由"><a href="#4-路由" class="headerlink" title="4. 路由"></a>4. 路由</h1><h2 id="4-1-【对路由的理解】"><a href="#4-1-【对路由的理解】" class="headerlink" title="4.1. 【对路由的理解】"></a>4.1. 【对路由的理解】</h2><img src="../../../../post_img/0326/Vue3learning/image-20231018144351536.png" srcset="/blog/img/loading.gif" lazyload alt="image-20231018144351536" style="zoom:20%;border-radius:40px" /> 

<h2 id="4-2-【基本切换效果】"><a href="#4-2-【基本切换效果】" class="headerlink" title="4.2. 【基本切换效果】"></a>4.2. 【基本切换效果】</h2><ul>
<li><p><code>Vue3</code>中要使用<code>vue-router</code>的最新版本，目前是<code>4</code>版本。</p>
</li>
<li><p>路由配置文件代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123;createRouter,createWebHistory&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue-router&#x27;</span><br><span class="hljs-keyword">import</span> <span class="hljs-title class_">Home</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@/pages/Home.vue&#x27;</span><br><span class="hljs-keyword">import</span> <span class="hljs-title class_">News</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@/pages/News.vue&#x27;</span><br><span class="hljs-keyword">import</span> <span class="hljs-title class_">About</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@/pages/About.vue&#x27;</span><br><br><span class="hljs-keyword">const</span> router = <span class="hljs-title function_">createRouter</span>(&#123;<br>	<span class="hljs-attr">history</span>:<span class="hljs-title function_">createWebHistory</span>(),<br>	<span class="hljs-attr">routes</span>:[<br>		&#123;<br>			<span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;/home&#x27;</span>,<br>			<span class="hljs-attr">component</span>:<span class="hljs-title class_">Home</span><br>		&#125;,<br>		&#123;<br>			<span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;/about&#x27;</span>,<br>			<span class="hljs-attr">component</span>:<span class="hljs-title class_">About</span><br>		&#125;<br>	]<br>&#125;)<br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> router<br></code></pre></td></tr></table></figure></li>
</ul>
<ul>
<li><p><code>main.ts</code>代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> router <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./router/index&#x27;</span><br>app.<span class="hljs-title function_">use</span>(router)<br><br>app.<span class="hljs-title function_">mount</span>(<span class="hljs-string">&#x27;#app&#x27;</span>)<br></code></pre></td></tr></table></figure></li>
</ul>
<ul>
<li><p><code>App.vue</code>代码如下</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;app&quot;&gt;<br>    &lt;h2 class=&quot;title&quot;&gt;Vue路由测试&lt;/h2&gt;<br>    &lt;!-- 导航区 --&gt;<br>    &lt;div class=&quot;navigate&quot;&gt;<br>      &lt;RouterLink to=&quot;/home&quot; active-class=&quot;active&quot;&gt;首页&lt;/RouterLink&gt;<br>      &lt;RouterLink to=&quot;/news&quot; active-class=&quot;active&quot;&gt;新闻&lt;/RouterLink&gt;<br>      &lt;RouterLink to=&quot;/about&quot; active-class=&quot;active&quot;&gt;关于&lt;/RouterLink&gt;<br>    &lt;/div&gt;<br>    &lt;!-- 展示区 --&gt;<br>    &lt;div class=&quot;main-content&quot;&gt;<br>      &lt;RouterView&gt;&lt;/RouterView&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script lang=&quot;ts&quot; setup name=&quot;App&quot;&gt;<br>  import &#123;RouterLink,RouterView&#125; from &#x27;vue-router&#x27;  <br>&lt;/script&gt;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="4-3-【两个注意点】"><a href="#4-3-【两个注意点】" class="headerlink" title="4.3. 【两个注意点】"></a>4.3. 【两个注意点】</h2><blockquote>
<ol>
<li><p>路由组件通常存放在<code>pages</code> 或 <code>views</code>文件夹，一般组件通常存放在<code>components</code>文件夹。</p>
</li>
<li><p>通过点击导航，视觉效果上“消失” 了的路由组件，默认是被<strong>卸载</strong>掉的，需要的时候再去<strong>挂载</strong>。</p>
</li>
</ol>
</blockquote>
<h2 id="4-4-【路由器工作模式】"><a href="#4-4-【路由器工作模式】" class="headerlink" title="4.4.【路由器工作模式】"></a>4.4.【路由器工作模式】</h2><ol>
<li><p><code>history</code>模式</p>
<blockquote>
<p>优点：<code>URL</code>更加美观，不带有<code>#</code>，更接近传统的网站<code>URL</code>。</p>
<p>缺点：后期项目上线，需要服务端配合处理路径问题，否则刷新会有<code>404</code>错误。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> router = <span class="hljs-title function_">createRouter</span>(&#123;<br>	<span class="hljs-attr">history</span>:<span class="hljs-title function_">createWebHistory</span>(), <span class="hljs-comment">//history模式</span><br>	<span class="hljs-comment">/******/</span><br>&#125;)<br></code></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p><code>hash</code>模式</p>
<blockquote>
<p>优点：兼容性更好，因为不需要服务器端处理路径。</p>
<p>缺点：<code>URL</code>带有<code>#</code>不太美观，且在<code>SEO</code>优化方面相对较差。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> router = <span class="hljs-title function_">createRouter</span>(&#123;<br>	<span class="hljs-attr">history</span>:<span class="hljs-title function_">createWebHashHistory</span>(), <span class="hljs-comment">//hash模式</span><br>	<span class="hljs-comment">/******/</span><br>&#125;)<br></code></pre></td></tr></table></figure></blockquote>
</li>
</ol>
<h2 id="4-5-【to的两种写法】"><a href="#4-5-【to的两种写法】" class="headerlink" title="4.5. 【to的两种写法】"></a>4.5. 【to的两种写法】</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;!-- 第一种：to的字符串写法 --&gt;<br>&lt;router-link active-class=&quot;active&quot; to=&quot;/home&quot;&gt;主页&lt;/router-link&gt;<br><br>&lt;!-- 第二种：to的对象写法 --&gt;<br>&lt;router-link active-class=&quot;active&quot; :to=&quot;&#123;path:&#x27;/home&#x27;&#125;&quot;&gt;Home&lt;/router-link&gt;<br></code></pre></td></tr></table></figure>

<h2 id="4-6-【命名路由】"><a href="#4-6-【命名路由】" class="headerlink" title="4.6. 【命名路由】"></a>4.6. 【命名路由】</h2><p>作用：可以简化路由跳转及传参（后面就讲）。</p>
<p>给路由规则命名：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-attr">routes</span>:[<br>  &#123;<br>    <span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;zhuye&#x27;</span>,<br>    <span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;/home&#x27;</span>,<br>    <span class="hljs-attr">component</span>:<span class="hljs-title class_">Home</span><br>  &#125;,<br>  &#123;<br>    <span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;xinwen&#x27;</span>,<br>    <span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;/news&#x27;</span>,<br>    <span class="hljs-attr">component</span>:<span class="hljs-title class_">News</span>,<br>  &#125;,<br>  &#123;<br>    <span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;guanyu&#x27;</span>,<br>    <span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;/about&#x27;</span>,<br>    <span class="hljs-attr">component</span>:<span class="hljs-title class_">About</span><br>  &#125;<br>]<br></code></pre></td></tr></table></figure>

<p>跳转路由：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;!--简化前：需要写完整的路径（to的字符串写法） --&gt;<br>&lt;router-link to=&quot;/news/detail&quot;&gt;跳转&lt;/router-link&gt;<br><br>&lt;!--简化后：直接通过名字跳转（to的对象写法配合name属性） --&gt;<br>&lt;router-link :to=&quot;&#123;name:&#x27;guanyu&#x27;&#125;&quot;&gt;跳转&lt;/router-link&gt;<br></code></pre></td></tr></table></figure>



<h2 id="4-7-【嵌套路由】"><a href="#4-7-【嵌套路由】" class="headerlink" title="4.7. 【嵌套路由】"></a>4.7. 【嵌套路由】</h2><ol>
<li><p>编写<code>News</code>的子路由：<code>Detail.vue</code></p>
</li>
<li><p>配置路由规则，使用<code>children</code>配置项：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">const</span> router = <span class="hljs-title function_">createRouter</span>(&#123;<br>  <span class="hljs-attr">history</span>:<span class="hljs-title function_">createWebHistory</span>(),<br>	<span class="hljs-attr">routes</span>:[<br>		&#123;<br>			<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;zhuye&#x27;</span>,<br>			<span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;/home&#x27;</span>,<br>			<span class="hljs-attr">component</span>:<span class="hljs-title class_">Home</span><br>		&#125;,<br>		&#123;<br>			<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;xinwen&#x27;</span>,<br>			<span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;/news&#x27;</span>,<br>			<span class="hljs-attr">component</span>:<span class="hljs-title class_">News</span>,<br>			<span class="hljs-attr">children</span>:[<br>				&#123;<br>					<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;xiang&#x27;</span>,<br>					<span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;detail&#x27;</span>,<br>					<span class="hljs-attr">component</span>:<span class="hljs-title class_">Detail</span><br>				&#125;<br>			]<br>		&#125;,<br>		&#123;<br>			<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;guanyu&#x27;</span>,<br>			<span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;/about&#x27;</span>,<br>			<span class="hljs-attr">component</span>:<span class="hljs-title class_">About</span><br>		&#125;<br>	]<br>&#125;)<br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> router<br></code></pre></td></tr></table></figure>
</li>
<li><p>跳转路由（记得要加完整路径）：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;router-link to=&quot;/news/detail&quot;&gt;xxxx&lt;/router-link&gt;<br>&lt;!-- 或 --&gt;<br>&lt;router-link :to=&quot;&#123;path:&#x27;/news/detail&#x27;&#125;&quot;&gt;xxxx&lt;/router-link&gt;<br></code></pre></td></tr></table></figure>
</li>
<li><p>记得去<code>Home</code>组件中预留一个<code>&lt;router-view&gt;</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;news&quot;&gt;<br>    &lt;nav class=&quot;news-list&quot;&gt;<br>      &lt;RouterLink v-for=&quot;news in newsList&quot; :key=&quot;news.id&quot; :to=&quot;&#123;path:&#x27;/news/detail&#x27;&#125;&quot;&gt;<br>        &#123;&#123;news.name&#125;&#125;<br>      &lt;/RouterLink&gt;<br>    &lt;/nav&gt;<br>    &lt;div class=&quot;news-detail&quot;&gt;<br>      &lt;RouterView/&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="4-8-【路由传参】"><a href="#4-8-【路由传参】" class="headerlink" title="4.8. 【路由传参】"></a>4.8. 【路由传参】</h2><h3 id="query参数"><a href="#query参数" class="headerlink" title="query参数"></a>query参数</h3><ol>
<li><p>传递参数</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;!-- 跳转并携带query参数（to的字符串写法） --&gt;<br>&lt;router-link to=&quot;/news/detail?a=1&amp;b=2&amp;content=欢迎你&quot;&gt;<br>	跳转<br>&lt;/router-link&gt;<br>				<br>&lt;!-- 跳转并携带query参数（to的对象写法） --&gt;<br>&lt;RouterLink <br>  :to=&quot;&#123;<br>    //name:&#x27;xiang&#x27;, //用name也可以跳转<br>    path:&#x27;/news/detail&#x27;,<br>    query:&#123;<br>      id:news.id,<br>      title:news.title,<br>      content:news.content<br>    &#125;<br>  &#125;&quot;<br>&gt;<br>  &#123;&#123;news.title&#125;&#125;<br>&lt;/RouterLink&gt;<br></code></pre></td></tr></table></figure>
</li>
<li><p>接收参数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123;useRoute&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue-router&#x27;</span><br><span class="hljs-keyword">const</span> route = <span class="hljs-title function_">useRoute</span>()<br><span class="hljs-comment">// 打印query参数</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(route.<span class="hljs-property">query</span>)<br></code></pre></td></tr></table></figure></li>
</ol>
<h3 id="params参数"><a href="#params参数" class="headerlink" title="params参数"></a>params参数</h3><ol>
<li><p>传递参数</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;!-- 跳转并携带params参数（to的字符串写法） --&gt;<br>&lt;RouterLink :to=&quot;`/news/detail/001/新闻001/内容001`&quot;&gt;&#123;&#123;news.title&#125;&#125;&lt;/RouterLink&gt;<br>				<br>&lt;!-- 跳转并携带params参数（to的对象写法） --&gt;<br>&lt;RouterLink <br>  :to=&quot;&#123;<br>    name:&#x27;xiang&#x27;, //用name跳转<br>    params:&#123;<br>      id:news.id,<br>      title:news.title,<br>      content:news.title<br>    &#125;<br>  &#125;&quot;<br>&gt;<br>  &#123;&#123;news.title&#125;&#125;<br>&lt;/RouterLink&gt;<br></code></pre></td></tr></table></figure>
</li>
<li><p>接收参数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123;useRoute&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue-router&#x27;</span><br><span class="hljs-keyword">const</span> route = <span class="hljs-title function_">useRoute</span>()<br><span class="hljs-comment">// 打印params参数</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(route.<span class="hljs-property">params</span>)<br></code></pre></td></tr></table></figure></li>
</ol>
<blockquote>
<p>备注1：传递<code>params</code>参数时，若使用<code>to</code>的对象写法，必须使用<code>name</code>配置项，不能用<code>path</code>。</p>
<p>备注2：传递<code>params</code>参数时，需要提前在规则中占位。</p>
</blockquote>
<h2 id="4-9-【路由的props配置】"><a href="#4-9-【路由的props配置】" class="headerlink" title="4.9. 【路由的props配置】"></a>4.9. 【路由的props配置】</h2><p>作用：让路由组件更方便的收到参数（可以将路由参数作为<code>props</code>传给组件）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js">&#123;<br>	<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;xiang&#x27;</span>,<br>	<span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;detail/:id/:title/:content&#x27;</span>,<br>	<span class="hljs-attr">component</span>:<span class="hljs-title class_">Detail</span>,<br><br>  <span class="hljs-comment">// props的对象写法，作用：把对象中的每一组key-value作为props传给Detail组件</span><br>  <span class="hljs-comment">// props:&#123;a:1,b:2,c:3&#125;, </span><br><br>  <span class="hljs-comment">// props的布尔值写法，作用：把收到了每一组params参数，作为props传给Detail组件</span><br>  <span class="hljs-comment">// props:true</span><br>  <br>  <span class="hljs-comment">// props的函数写法，作用：把返回的对象中每一组key-value作为props传给Detail组件</span><br>  <span class="hljs-title function_">props</span>(<span class="hljs-params">route</span>)&#123;<br>    <span class="hljs-keyword">return</span> route.<span class="hljs-property">query</span><br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="4-10-【-replace属性】"><a href="#4-10-【-replace属性】" class="headerlink" title="4.10. 【 replace属性】"></a>4.10. 【 replace属性】</h2><ol>
<li><p>作用：控制路由跳转时操作浏览器历史记录的模式。</p>
</li>
<li><p>浏览器的历史记录有两种写入方式：分别为<code>push</code>和<code>replace</code>：</p>
<ul>
<li><code>push</code>是追加历史记录（默认值）。</li>
<li><code>replace</code>是替换当前记录。</li>
</ul>
</li>
<li><p>开启<code>replace</code>模式：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;RouterLink replace .......&gt;News&lt;/RouterLink&gt;<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="4-11-【编程式导航】"><a href="#4-11-【编程式导航】" class="headerlink" title="4.11. 【编程式导航】"></a>4.11. 【编程式导航】</h2><p>路由组件的两个重要的属性：<code>$route</code>和<code>$router</code>变成了两个<code>hooks</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123;useRoute,useRouter&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue-router&#x27;</span><br><br><span class="hljs-keyword">const</span> route = <span class="hljs-title function_">useRoute</span>()<br><span class="hljs-keyword">const</span> router = <span class="hljs-title function_">useRouter</span>()<br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(route.<span class="hljs-property">query</span>)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(route.<span class="hljs-property">parmas</span>)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(router.<span class="hljs-property">push</span>)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(router.<span class="hljs-property">replace</span>)<br></code></pre></td></tr></table></figure>

<h2 id="4-12-【重定向】"><a href="#4-12-【重定向】" class="headerlink" title="4.12. 【重定向】"></a>4.12. 【重定向】</h2><ol>
<li><p>作用：将特定的路径，重新定向到已有路由。</p>
</li>
<li><p>具体编码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js">&#123;<br>    <span class="hljs-attr">path</span>:<span class="hljs-string">&#x27;/&#x27;</span>,<br>    <span class="hljs-attr">redirect</span>:<span class="hljs-string">&#x27;/about&#x27;</span><br>&#125;<br></code></pre></td></tr></table></figure></li>
</ol>
<h1 id="5-pinia"><a href="#5-pinia" class="headerlink" title="5. pinia"></a>5. pinia</h1><h2 id="5-1【准备一个效果】"><a href="#5-1【准备一个效果】" class="headerlink" title="5.1【准备一个效果】"></a>5.1【准备一个效果】</h2><img src="../../../../post_img/0326/Vue3learning/pinia_example.gif" srcset="/blog/img/loading.gif" lazyload alt="pinia_example" style="zoom:30%;border:3px solid" /> 

<h2 id="5-2【搭建-pinia-环境】"><a href="#5-2【搭建-pinia-环境】" class="headerlink" title="5.2【搭建 pinia 环境】"></a>5.2【搭建 pinia 环境】</h2><p>第一步：<code>npm install pinia</code></p>
<p>第二步：操作<code>src/main.ts</code></p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">import</span> &#123; createApp &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><span class="hljs-keyword">import</span> <span class="hljs-title class_">App</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./App.vue&#x27;</span><br><br><span class="hljs-comment">/* 引入createPinia，用于创建pinia */</span><br><span class="hljs-keyword">import</span> &#123; createPinia &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;pinia&#x27;</span><br><br><span class="hljs-comment">/* 创建pinia */</span><br><span class="hljs-keyword">const</span> pinia = <span class="hljs-title function_">createPinia</span>()<br><span class="hljs-keyword">const</span> app = <span class="hljs-title function_">createApp</span>(<span class="hljs-title class_">App</span>)<br><br><span class="hljs-comment">/* 使用插件 */</span>&#123;&#125;<br>app.<span class="hljs-title function_">use</span>(pinia)<br>app.<span class="hljs-title function_">mount</span>(<span class="hljs-string">&#x27;#app&#x27;</span>)<br></code></pre></td></tr></table></figure>

<p>此时开发者工具中已经有了<code>pinia</code>选项</p>
<img src="https://cdn.nlark.com/yuque/0/2023/png/35780599/1684309952481-c67f67f9-d1a3-4d69-8bd6-2b381e003f31.png" srcset="/blog/img/loading.gif" lazyload style="zoom:80%;border:1px solid black;border-radius:10px" />

<h2 id="5-3【存储-读取数据】"><a href="#5-3【存储-读取数据】" class="headerlink" title="5.3【存储+读取数据】"></a>5.3【存储+读取数据】</h2><ol>
<li><p><code>Store</code>是一个保存：<strong>状态</strong>、<strong>业务逻辑</strong> 的实体，每个组件都可以<strong>读取</strong>、<strong>写入</strong>它。</p>
</li>
<li><p>它有三个概念：<code>state</code>、<code>getter</code>、<code>action</code>，相当于组件中的： <code>data</code>、 <code>computed</code> 和 <code>methods</code>。</p>
</li>
<li><p>具体编码：<code>src/store/count.ts</code></p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-comment">// 引入defineStore用于创建store</span><br><span class="hljs-keyword">import</span> &#123;defineStore&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;pinia&#x27;</span><br><br><span class="hljs-comment">// 定义并暴露一个store</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> useCountStore = <span class="hljs-title function_">defineStore</span>(<span class="hljs-string">&#x27;count&#x27;</span>,&#123;<br>  <span class="hljs-comment">// 动作</span><br>  <span class="hljs-attr">actions</span>:&#123;&#125;,<br>  <span class="hljs-comment">// 状态</span><br>  <span class="hljs-title function_">state</span>(<span class="hljs-params"></span>)&#123;<br>    <span class="hljs-keyword">return</span> &#123;<br>      <span class="hljs-attr">sum</span>:<span class="hljs-number">6</span><br>    &#125;<br>  &#125;,<br>  <span class="hljs-comment">// 计算</span><br>  <span class="hljs-attr">getters</span>:&#123;&#125;<br>&#125;)<br></code></pre></td></tr></table></figure>
</li>
<li><p>具体编码：<code>src/store/talk.ts</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 引入defineStore用于创建store</span><br><span class="hljs-keyword">import</span> &#123;defineStore&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;pinia&#x27;</span><br><br><span class="hljs-comment">// 定义并暴露一个store</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> useTalkStore = <span class="hljs-title function_">defineStore</span>(<span class="hljs-string">&#x27;talk&#x27;</span>,&#123;<br>  <span class="hljs-comment">// 动作</span><br>  <span class="hljs-attr">actions</span>:&#123;&#125;,<br>  <span class="hljs-comment">// 状态</span><br>  <span class="hljs-title function_">state</span>(<span class="hljs-params"></span>)&#123;<br>    <span class="hljs-keyword">return</span> &#123;<br>      <span class="hljs-attr">talkList</span>:[<br>        &#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;yuysada01&#x27;</span>,<span class="hljs-attr">content</span>:<span class="hljs-string">&#x27;你今天有点怪，哪里怪？怪好看的！&#x27;</span>&#125;,<br>     		&#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;yuysada02&#x27;</span>,<span class="hljs-attr">content</span>:<span class="hljs-string">&#x27;草莓、蓝莓、蔓越莓，你想我了没？&#x27;</span>&#125;,<br>        &#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;yuysada03&#x27;</span>,<span class="hljs-attr">content</span>:<span class="hljs-string">&#x27;心里给你留了一块地，我的死心塌地&#x27;</span>&#125;<br>      ]<br>    &#125;<br>  &#125;,<br>  <span class="hljs-comment">// 计算</span><br>  <span class="hljs-attr">getters</span>:&#123;&#125;<br>&#125;)<br></code></pre></td></tr></table></figure>
</li>
<li><p>组件中使用<code>state</code>中的数据</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;h2&gt;当前求和为：&#123;&#123; sumStore.sum &#125;&#125;&lt;/h2&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;Count&quot;&gt;<br>  // 引入对应的useXxxxxStore	<br>  import &#123;useSumStore&#125; from &#x27;@/store/sum&#x27;<br>  <br>  // 调用useXxxxxStore得到对应的store<br>  const sumStore = useSumStore()<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;ul&gt;<br>    &lt;li v-for=&quot;talk in talkStore.talkList&quot; :key=&quot;talk.id&quot;&gt;<br>      &#123;&#123; talk.content &#125;&#125;<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;Count&quot;&gt;<br>  import axios from &#x27;axios&#x27;<br>  import &#123;useTalkStore&#125; from &#x27;@/store/talk&#x27;<br><br>  const talkStore = useTalkStore()<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="5-4-【修改数据】-三种方式"><a href="#5-4-【修改数据】-三种方式" class="headerlink" title="5.4.【修改数据】(三种方式)"></a>5.4.【修改数据】(三种方式)</h2><ol>
<li><p>第一种修改方式，直接修改</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ts">countStore.<span class="hljs-property">sum</span> = <span class="hljs-number">666</span><br></code></pre></td></tr></table></figure>
</li>
<li><p>第二种修改方式：批量修改</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs ts">countStore.$patch(&#123;<br>  <span class="hljs-attr">sum</span>:<span class="hljs-number">999</span>,<br>  <span class="hljs-attr">school</span>:<span class="hljs-string">&#x27;atguigu&#x27;</span><br>&#125;)<br></code></pre></td></tr></table></figure>
</li>
<li><p>第三种修改方式：借助<code>action</code>修改（<code>action</code>中可以编写一些业务逻辑）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123; defineStore &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;pinia&#x27;</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> useCountStore = <span class="hljs-title function_">defineStore</span>(<span class="hljs-string">&#x27;count&#x27;</span>, &#123;<br>  <span class="hljs-comment">/*************/</span><br>  <span class="hljs-attr">actions</span>: &#123;<br>    <span class="hljs-comment">//加</span><br>    <span class="hljs-title function_">increment</span>(<span class="hljs-params">value:number</span>) &#123;<br>      <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">sum</span> &lt; <span class="hljs-number">10</span>) &#123;<br>        <span class="hljs-comment">//操作countStore中的sum</span><br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">sum</span> += value<br>      &#125;<br>    &#125;,<br>    <span class="hljs-comment">//减</span><br>    <span class="hljs-title function_">decrement</span>(<span class="hljs-params">value:number</span>)&#123;<br>      <span class="hljs-keyword">if</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">sum</span> &gt; <span class="hljs-number">1</span>)&#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">sum</span> -= value<br>      &#125;<br>    &#125;<br>  &#125;,<br>  <span class="hljs-comment">/*************/</span><br>&#125;)<br></code></pre></td></tr></table></figure>
</li>
<li><p>组件中调用<code>action</code>即可</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 使用countStore</span><br><span class="hljs-keyword">const</span> countStore = <span class="hljs-title function_">useCountStore</span>()<br><br><span class="hljs-comment">// 调用对应action</span><br>countStore.<span class="hljs-title function_">incrementOdd</span>(n.<span class="hljs-property">value</span>)<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="5-5-【storeToRefs】"><a href="#5-5-【storeToRefs】" class="headerlink" title="5.5.【storeToRefs】"></a>5.5.【storeToRefs】</h2><ul>
<li>借助<code>storeToRefs</code>将<code>store</code>中的数据转为<code>ref</code>对象，方便在模板中使用。</li>
<li>注意：<code>pinia</code>提供的<code>storeToRefs</code>只会将数据做转换，而<code>Vue</code>的<code>toRefs</code>会转换<code>store</code>中数据。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;div class=&quot;count&quot;&gt;<br>		&lt;h2&gt;当前求和为：&#123;&#123;sum&#125;&#125;&lt;/h2&gt;<br>	&lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;Count&quot;&gt;<br>  import &#123; useCountStore &#125; from &#x27;@/store/count&#x27;<br>  /* 引入storeToRefs */<br>  import &#123; storeToRefs &#125; from &#x27;pinia&#x27;<br><br>	/* 得到countStore */<br>  const countStore = useCountStore()<br>  /* 使用storeToRefs转换countStore，随后解构 */<br>  const &#123;sum&#125; = storeToRefs(countStore)<br>&lt;/script&gt;<br><br></code></pre></td></tr></table></figure>

<h2 id="5-6-【getters】"><a href="#5-6-【getters】" class="headerlink" title="5.6.【getters】"></a>5.6.【getters】</h2><ol>
<li><p>概念：当<code>state</code>中的数据，需要经过处理后再使用时，可以使用<code>getters</code>配置。</p>
</li>
<li><p>追加<code>getters</code>配置。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 引入defineStore用于创建store</span><br><span class="hljs-keyword">import</span> &#123;defineStore&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;pinia&#x27;</span><br><br><span class="hljs-comment">// 定义并暴露一个store</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> useCountStore = <span class="hljs-title function_">defineStore</span>(<span class="hljs-string">&#x27;count&#x27;</span>,&#123;<br>  <span class="hljs-comment">// 动作</span><br>  <span class="hljs-attr">actions</span>:&#123;<br>    <span class="hljs-comment">/************/</span><br>  &#125;,<br>  <span class="hljs-comment">// 状态</span><br>  <span class="hljs-title function_">state</span>(<span class="hljs-params"></span>)&#123;<br>    <span class="hljs-keyword">return</span> &#123;<br>      <span class="hljs-attr">sum</span>:<span class="hljs-number">1</span>,<br>      <span class="hljs-attr">school</span>:<span class="hljs-string">&#x27;atguigu&#x27;</span><br>    &#125;<br>  &#125;,<br>  <span class="hljs-comment">// 计算</span><br>  <span class="hljs-attr">getters</span>:&#123;<br>    <span class="hljs-attr">bigSum</span>:(state):<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> state.<span class="hljs-property">sum</span> *<span class="hljs-number">10</span>,<br>    <span class="hljs-title function_">upperSchool</span>():string&#123;<br>      <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>. school.<span class="hljs-title function_">toUpperCase</span>()<br>    &#125;<br>  &#125;<br>&#125;)<br></code></pre></td></tr></table></figure>
</li>
<li><p>组件中读取数据：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> &#123;increment,decrement&#125; = countStore<br><span class="hljs-keyword">let</span> &#123;sum,school,bigSum,upperSchool&#125; = <span class="hljs-title function_">storeToRefs</span>(countStore)<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="5-7-【-subscribe】"><a href="#5-7-【-subscribe】" class="headerlink" title="5.7.【$subscribe】"></a>5.7.【$subscribe】</h2><p>通过 store 的 <code>$subscribe()</code> 方法侦听 <code>state</code> 及其变化</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs ts">talkStore.$subscribe(<span class="hljs-function">(<span class="hljs-params">mutate,state</span>)=&gt;</span>&#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;LoveTalk&#x27;</span>,mutate,state)<br>  <span class="hljs-variable language_">localStorage</span>.<span class="hljs-title function_">setItem</span>(<span class="hljs-string">&#x27;talk&#x27;</span>,<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(talkList.<span class="hljs-property">value</span>))<br>&#125;)<br></code></pre></td></tr></table></figure>



<h2 id="5-8-【store组合式写法】"><a href="#5-8-【store组合式写法】" class="headerlink" title="5.8. 【store组合式写法】"></a>5.8. 【store组合式写法】</h2><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">import</span> &#123;defineStore&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;pinia&#x27;</span><br><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;axios&#x27;</span><br><span class="hljs-keyword">import</span> &#123;nanoid&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;nanoid&#x27;</span><br><span class="hljs-keyword">import</span> &#123;reactive&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> useTalkStore = <span class="hljs-title function_">defineStore</span>(<span class="hljs-string">&#x27;talk&#x27;</span>,<span class="hljs-function">()=&gt;</span>&#123;<br>  <span class="hljs-comment">// talkList就是state</span><br>  <span class="hljs-keyword">const</span> talkList = <span class="hljs-title function_">reactive</span>(<br>    <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-variable language_">localStorage</span>.<span class="hljs-title function_">getItem</span>(<span class="hljs-string">&#x27;talkList&#x27;</span>) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>) || []<br>  )<br><br>  <span class="hljs-comment">// getATalk函数相当于action</span><br>  <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getATalk</span>(<span class="hljs-params"></span>)&#123;<br>    <span class="hljs-comment">// 发请求，下面这行的写法是：连续解构赋值+重命名</span><br>    <span class="hljs-keyword">let</span> &#123;<span class="hljs-attr">data</span>:&#123;<span class="hljs-attr">content</span>:title&#125;&#125; = <span class="hljs-keyword">await</span> axios.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;https://api.uomg.com/api/rand.qinghua?format=json&#x27;</span>)<br>    <span class="hljs-comment">// 把请求回来的字符串，包装成一个对象</span><br>    <span class="hljs-keyword">let</span> obj = &#123;<span class="hljs-attr">id</span>:<span class="hljs-title function_">nanoid</span>(),title&#125;<br>    <span class="hljs-comment">// 放到数组中</span><br>    talkList.<span class="hljs-title function_">unshift</span>(obj)<br>  &#125;<br>  <span class="hljs-keyword">return</span> &#123;talkList,getATalk&#125;<br>&#125;)<br></code></pre></td></tr></table></figure>



<h1 id="6-组件通信"><a href="#6-组件通信" class="headerlink" title="6. 组件通信"></a>6. 组件通信</h1><p><strong><code>Vue3</code>组件通信和<code>Vue2</code>的区别：</strong></p>
<ul>
<li>移出事件总线，使用<code>mitt</code>代替。</li>
</ul>
<ul>
<li><code>vuex</code>换成了<code>pinia</code>。</li>
<li>把<code>.sync</code>优化到了<code>v-model</code>里面了。</li>
<li>把<code>$listeners</code>所有的东西，合并到<code>$attrs</code>中了。</li>
<li><code>$children</code>被砍掉了。</li>
</ul>
<p><strong>常见搭配形式：</strong></p>
<img src="../../../../post_img/0326/Vue3learning/image-20231119185900990.png" srcset="/blog/img/loading.gif" lazyload alt="image-20231119185900990" style="zoom:60%;" /> 

<h2 id="6-1-【props】"><a href="#6-1-【props】" class="headerlink" title="6.1. 【props】"></a>6.1. 【props】</h2><p>概述：<code>props</code>是使用频率最高的一种通信方式，常用与 ：<strong>父 ↔ 子</strong>。</p>
<ul>
<li>若 <strong>父传子</strong>：属性值是<strong>非函数</strong>。</li>
<li>若 <strong>子传父</strong>：属性值是<strong>函数</strong>。</li>
</ul>
<p>父组件：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;father&quot;&gt;<br>    &lt;h3&gt;父组件，&lt;/h3&gt;<br>		&lt;h4&gt;我的车：&#123;&#123; car &#125;&#125;&lt;/h4&gt;<br>		&lt;h4&gt;儿子给的玩具：&#123;&#123; toy &#125;&#125;&lt;/h4&gt;<br>		&lt;Child :car=&quot;car&quot; :getToy=&quot;getToy&quot;/&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;Father&quot;&gt;<br>	import Child from &#x27;./Child.vue&#x27;<br>	import &#123; ref &#125; from &quot;vue&quot;;<br>	// 数据<br>	const car = ref(&#x27;奔驰&#x27;)<br>	const toy = ref()<br>	// 方法<br>	function getToy(value:string)&#123;<br>		toy.value = value<br>	&#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>子组件</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;child&quot;&gt;<br>    &lt;h3&gt;子组件&lt;/h3&gt;<br>		&lt;h4&gt;我的玩具：&#123;&#123; toy &#125;&#125;&lt;/h4&gt;<br>		&lt;h4&gt;父给我的车：&#123;&#123; car &#125;&#125;&lt;/h4&gt;<br>		&lt;button @click=&quot;getToy(toy)&quot;&gt;玩具给父亲&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;Child&quot;&gt;<br>	import &#123; ref &#125; from &quot;vue&quot;;<br>	const toy = ref(&#x27;奥特曼&#x27;)<br>	<br>	defineProps([&#x27;car&#x27;,&#x27;getToy&#x27;])<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="6-2-【自定义事件】"><a href="#6-2-【自定义事件】" class="headerlink" title="6.2. 【自定义事件】"></a>6.2. 【自定义事件】</h2><ol>
<li>概述：自定义事件常用于：<strong>子 &#x3D;&gt; 父。</strong></li>
<li>注意区分好：原生事件、自定义事件。</li>
</ol>
<ul>
<li>原生事件：<ul>
<li>事件名是特定的（<code>click</code>、<code>mosueenter</code>等等）	</li>
<li>事件对象<code>$event</code>: 是包含事件相关信息的对象（<code>pageX</code>、<code>pageY</code>、<code>target</code>、<code>keyCode</code>）</li>
</ul>
</li>
<li>自定义事件：<ul>
<li>事件名是任意名称</li>
<li><strong style="color:red">事件对象<code>$event</code>: 是调用<code>emit</code>时所提供的数据，可以是任意类型！！！</strong ></li>
</ul>
</li>
</ul>
<ol start="3">
<li><p>示例：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-comment">&lt;!--在父组件中，给子组件绑定自定义事件：--&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">Child</span> @<span class="hljs-attr">send-toy</span>=<span class="hljs-string">&quot;toy = $event&quot;</span>/&gt;</span><br><br><span class="hljs-comment">&lt;!--注意区分原生事件与自定义事件中的$event--&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">&quot;toy = $event&quot;</span>&gt;</span>测试<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br></code></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//子组件中，触发事件：</span><br><span class="hljs-variable language_">this</span>.$emit(<span class="hljs-string">&#x27;send-toy&#x27;</span>, 具体数据)<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="6-3-【mitt】"><a href="#6-3-【mitt】" class="headerlink" title="6.3. 【mitt】"></a>6.3. 【mitt】</h2><p>概述：与消息订阅与发布（<code>pubsub</code>）功能类似，可以实现任意组件间通信。</p>
<p>安装<code>mitt</code></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">npm i mitt<br></code></pre></td></tr></table></figure>

<p>新建文件：<code>src\utils\emitter.ts</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// 引入mitt </span><br><span class="hljs-keyword">import</span> mitt <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;mitt&quot;</span>;<br><br><span class="hljs-comment">// 创建emitter</span><br><span class="hljs-keyword">const</span> emitter = <span class="hljs-title function_">mitt</span>()<br><br><span class="hljs-comment">/*</span><br><span class="hljs-comment">  // 绑定事件</span><br><span class="hljs-comment">  emitter.on(&#x27;abc&#x27;,(value)=&gt;&#123;</span><br><span class="hljs-comment">    console.log(&#x27;abc事件被触发&#x27;,value)</span><br><span class="hljs-comment">  &#125;)</span><br><span class="hljs-comment">  emitter.on(&#x27;xyz&#x27;,(value)=&gt;&#123;</span><br><span class="hljs-comment">    console.log(&#x27;xyz事件被触发&#x27;,value)</span><br><span class="hljs-comment">  &#125;)</span><br><span class="hljs-comment"></span><br><span class="hljs-comment">  setInterval(() =&gt; &#123;</span><br><span class="hljs-comment">    // 触发事件</span><br><span class="hljs-comment">    emitter.emit(&#x27;abc&#x27;,666)</span><br><span class="hljs-comment">    emitter.emit(&#x27;xyz&#x27;,777)</span><br><span class="hljs-comment">  &#125;, 1000);</span><br><span class="hljs-comment"></span><br><span class="hljs-comment">  setTimeout(() =&gt; &#123;</span><br><span class="hljs-comment">    // 清理事件</span><br><span class="hljs-comment">    emitter.all.clear()</span><br><span class="hljs-comment">  &#125;, 3000); </span><br><span class="hljs-comment">*/</span><br><br><span class="hljs-comment">// 创建并暴露mitt</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> emitter<br></code></pre></td></tr></table></figure>

<p>接收数据的组件中：绑定事件、同时在销毁前解绑事件：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">import</span> emitter <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;@/utils/emitter&quot;</span>;<br><span class="hljs-keyword">import</span> &#123; onUnmounted &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;vue&quot;</span>;<br><br><span class="hljs-comment">// 绑定事件</span><br>emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">&#x27;send-toy&#x27;</span>,<span class="hljs-function">(<span class="hljs-params">value</span>)=&gt;</span>&#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;send-toy事件被触发&#x27;</span>,value)<br>&#125;)<br><br><span class="hljs-title function_">onUnmounted</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>  <span class="hljs-comment">// 解绑事件</span><br>  emitter.<span class="hljs-title function_">off</span>(<span class="hljs-string">&#x27;send-toy&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>【第三步】：提供数据的组件，在合适的时候触发事件</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> emitter <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;@/utils/emitter&quot;</span>;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">sendToy</span>(<span class="hljs-params"></span>)&#123;<br>  <span class="hljs-comment">// 触发事件</span><br>  emitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">&#x27;send-toy&#x27;</span>,toy.<span class="hljs-property">value</span>)<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>注意这个重要的内置关系，总线依赖着这个内置关系</strong></p>
<h2 id="6-4-【v-model】"><a href="#6-4-【v-model】" class="headerlink" title="6.4.【v-model】"></a>6.4.【v-model】</h2><ol>
<li><p>概述：实现 <strong>父↔子</strong> 之间相互通信。</p>
</li>
<li><p>前序知识 —— <code>v-model</code>的本质</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;!-- 使用v-model指令 --&gt;<br>&lt;input type=&quot;text&quot; v-model=&quot;userName&quot;&gt;<br><br>&lt;!-- v-model的本质是下面这行代码 --&gt;<br>&lt;input <br>  type=&quot;text&quot; <br>  :value=&quot;userName&quot; <br>  @input=&quot;userName =(&lt;HTMLInputElement&gt;$event.target).value&quot;<br>&gt;<br></code></pre></td></tr></table></figure>
</li>
<li><p>组件标签上的<code>v-model</code>的本质：<code>:moldeValue</code> ＋ <code>update:modelValue</code>事件。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;!-- 组件标签上使用v-model指令 --&gt;<br>&lt;AtguiguInput v-model=&quot;userName&quot;/&gt;<br><br>&lt;!-- 组件标签上v-model的本质 --&gt;<br>&lt;AtguiguInput :modelValue=&quot;userName&quot; @update:model-value=&quot;userName = $event&quot;/&gt;<br></code></pre></td></tr></table></figure>

<p><code>AtguiguInput</code>组件中：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;box&quot;&gt;<br>    &lt;!--将接收的value值赋给input元素的value属性，目的是：为了呈现数据 --&gt;<br>		&lt;!--给input元素绑定原生input事件，触发input事件时，进而触发update:model-value事件--&gt;<br>    &lt;input <br>       type=&quot;text&quot; <br>       :value=&quot;modelValue&quot; <br>       @input=&quot;emit(&#x27;update:model-value&#x27;,$event.target.value)&quot;<br>    &gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;AtguiguInput&quot;&gt;<br>  // 接收props<br>  defineProps([&#x27;modelValue&#x27;])<br>  // 声明事件<br>  const emit = defineEmits([&#x27;update:model-value&#x27;])<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>
</li>
<li><p>也可以更换<code>value</code>，例如改成<code>abc</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;!-- 也可以更换value，例如改成abc--&gt;<br>&lt;AtguiguInput v-model:abc=&quot;userName&quot;/&gt;<br><br>&lt;!-- 上面代码的本质如下 --&gt;<br>&lt;AtguiguInput :abc=&quot;userName&quot; @update:abc=&quot;userName = $event&quot;/&gt;<br></code></pre></td></tr></table></figure>

<p><code>AtguiguInput</code>组件中：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;box&quot;&gt;<br>    &lt;input <br>       type=&quot;text&quot; <br>       :value=&quot;abc&quot; <br>       @input=&quot;emit(&#x27;update:abc&#x27;,$event.target.value)&quot;<br>    &gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;AtguiguInput&quot;&gt;<br>  // 接收props<br>  defineProps([&#x27;abc&#x27;])<br>  // 声明事件<br>  const emit = defineEmits([&#x27;update:abc&#x27;])<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>
</li>
<li><p>如果<code>value</code>可以更换，那么就可以在组件标签上多次使用<code>v-model</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;AtguiguInput v-model:abc=&quot;userName&quot; v-model:xyz=&quot;password&quot;/&gt;<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="6-5-【-attrs-】"><a href="#6-5-【-attrs-】" class="headerlink" title="6.5.【$attrs 】"></a>6.5.【$attrs 】</h2><ol>
<li><p>概述：<code>$attrs</code>用于实现<strong>当前组件的父组件</strong>，向<strong>当前组件的子组件</strong>通信（<strong>祖→孙</strong>）。</p>
</li>
<li><p>具体说明：<code>$attrs</code>是一个对象，包含所有父组件传入的标签属性。</p>
<blockquote>
<p> 注意：<code>$attrs</code>会自动排除<code>props</code>中声明的属性(可以认为声明过的 <code>props</code> 被子组件自己“消费”了)</p>
</blockquote>
</li>
</ol>
<p>父组件：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;father&quot;&gt;<br>    &lt;h3&gt;父组件&lt;/h3&gt;<br>		&lt;Child :a=&quot;a&quot; :b=&quot;b&quot; :c=&quot;c&quot; :d=&quot;d&quot; v-bind=&quot;&#123;x:100,y:200&#125;&quot; :updateA=&quot;updateA&quot;/&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;Father&quot;&gt;<br>	import Child from &#x27;./Child.vue&#x27;<br>	import &#123; ref &#125; from &quot;vue&quot;;<br>	let a = ref(1)<br>	let b = ref(2)<br>	let c = ref(3)<br>	let d = ref(4)<br><br>	function updateA(value)&#123;<br>		a.value = value<br>	&#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>子组件：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;div class=&quot;child&quot;&gt;<br>		&lt;h3&gt;子组件&lt;/h3&gt;<br>		&lt;GrandChild v-bind=&quot;$attrs&quot;/&gt;<br>	&lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;Child&quot;&gt;<br>	import GrandChild from &#x27;./GrandChild.vue&#x27;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>孙组件：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;div class=&quot;grand-child&quot;&gt;<br>		&lt;h3&gt;孙组件&lt;/h3&gt;<br>		&lt;h4&gt;a：&#123;&#123; a &#125;&#125;&lt;/h4&gt;<br>		&lt;h4&gt;b：&#123;&#123; b &#125;&#125;&lt;/h4&gt;<br>		&lt;h4&gt;c：&#123;&#123; c &#125;&#125;&lt;/h4&gt;<br>		&lt;h4&gt;d：&#123;&#123; d &#125;&#125;&lt;/h4&gt;<br>		&lt;h4&gt;x：&#123;&#123; x &#125;&#125;&lt;/h4&gt;<br>		&lt;h4&gt;y：&#123;&#123; y &#125;&#125;&lt;/h4&gt;<br>		&lt;button @click=&quot;updateA(666)&quot;&gt;点我更新A&lt;/button&gt;<br>	&lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;GrandChild&quot;&gt;<br>	defineProps([&#x27;a&#x27;,&#x27;b&#x27;,&#x27;c&#x27;,&#x27;d&#x27;,&#x27;x&#x27;,&#x27;y&#x27;,&#x27;updateA&#x27;])<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="6-6-【-refs、-parent】"><a href="#6-6-【-refs、-parent】" class="headerlink" title="6.6. 【$refs、$parent】"></a>6.6. 【$refs、$parent】</h2><ol>
<li><p>概述：</p>
<ul>
<li><code>$refs</code>用于 ：<strong>父→子。</strong></li>
<li><code>$parent</code>用于：<strong>子→父。</strong></li>
</ul>
</li>
<li><p>原理如下：</p>
<table>
<thead>
<tr>
<th>属性</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td><code>$refs</code></td>
<td>值为对象，包含所有被<code>ref</code>属性标识的<code>DOM</code>元素或组件实例。</td>
</tr>
<tr>
<td><code>$parent</code></td>
<td>值为对象，当前组件的父组件实例对象。</td>
</tr>
</tbody></table>
</li>
</ol>
<h2 id="6-7-【provide、inject】"><a href="#6-7-【provide、inject】" class="headerlink" title="6.7. 【provide、inject】"></a>6.7. 【provide、inject】</h2><ol>
<li><p>概述：实现<strong>祖孙组件</strong>直接通信</p>
</li>
<li><p>具体使用：</p>
<ul>
<li>在祖先组件中通过<code>provide</code>配置向后代组件提供数据</li>
<li>在后代组件中通过<code>inject</code>配置来声明接收数据</li>
</ul>
</li>
<li><p>具体编码：</p>
<p>【第一步】父组件中，使用<code>provide</code>提供数据</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;father&quot;&gt;<br>    &lt;h3&gt;父组件&lt;/h3&gt;<br>    &lt;h4&gt;资产：&#123;&#123; money &#125;&#125;&lt;/h4&gt;<br>    &lt;h4&gt;汽车：&#123;&#123; car &#125;&#125;&lt;/h4&gt;<br>    &lt;button @click=&quot;money += 1&quot;&gt;资产+1&lt;/button&gt;<br>    &lt;button @click=&quot;car.price += 1&quot;&gt;汽车价格+1&lt;/button&gt;<br>    &lt;Child/&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;Father&quot;&gt;<br>  import Child from &#x27;./Child.vue&#x27;<br>  import &#123; ref,reactive,provide &#125; from &quot;vue&quot;;<br>  // 数据<br>  let money = ref(100)<br>  let car = reactive(&#123;<br>    brand:&#x27;奔驰&#x27;,<br>    price:100<br>  &#125;)<br>  // 用于更新money的方法<br>  function updateMoney(value:number)&#123;<br>    money.value += value<br>  &#125;<br>  // 提供数据<br>  provide(&#x27;moneyContext&#x27;,&#123;money,updateMoney&#125;)<br>  provide(&#x27;car&#x27;,car)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>注意：子组件中不用编写任何东西，是不受到任何打扰的</p>
</blockquote>
<p>【第二步】孙组件中使用<code>inject</code>配置项接受数据。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div class=&quot;grand-child&quot;&gt;<br>    &lt;h3&gt;我是孙组件&lt;/h3&gt;<br>    &lt;h4&gt;资产：&#123;&#123; money &#125;&#125;&lt;/h4&gt;<br>    &lt;h4&gt;汽车：&#123;&#123; car &#125;&#125;&lt;/h4&gt;<br>    &lt;button @click=&quot;updateMoney(6)&quot;&gt;点我&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot; name=&quot;GrandChild&quot;&gt;<br>  import &#123; inject &#125; from &#x27;vue&#x27;;<br>  // 注入数据<br> let &#123;money,updateMoney&#125; = inject(&#x27;moneyContext&#x27;,&#123;money:0,updateMoney:(x:number)=&gt;&#123;&#125;&#125;)<br>  let car = inject(&#x27;car&#x27;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="6-8-【pinia】"><a href="#6-8-【pinia】" class="headerlink" title="6.8. 【pinia】"></a>6.8. 【pinia】</h2><p>参考之前<code>pinia</code>部分的讲解</p>
<h2 id="6-9-【slot】"><a href="#6-9-【slot】" class="headerlink" title="6.9. 【slot】"></a>6.9. 【slot】</h2><h3 id="1-默认插槽"><a href="#1-默认插槽" class="headerlink" title="1. 默认插槽"></a>1. 默认插槽</h3><img src='https://gitee.com/isolace/pichome/raw/master/img/1711457814487.jpg'>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs vue">父组件中：<br>        &lt;Category title=&quot;今日热门游戏&quot;&gt;<br>          &lt;ul&gt;<br>            &lt;li v-for=&quot;g in games&quot; :key=&quot;g.id&quot;&gt;&#123;&#123; g.name &#125;&#125;&lt;/li&gt;<br>          &lt;/ul&gt;<br>        &lt;/Category&gt;<br>子组件中：<br>        &lt;template&gt;<br>          &lt;div class=&quot;item&quot;&gt;<br>            &lt;h3&gt;&#123;&#123; title &#125;&#125;&lt;/h3&gt;<br>            &lt;!-- 默认插槽 --&gt;<br>            &lt;slot&gt;&lt;/slot&gt;<br>          &lt;/div&gt;<br>        &lt;/template&gt;<br></code></pre></td></tr></table></figure>

<h3 id="2-具名插槽"><a href="#2-具名插槽" class="headerlink" title="2. 具名插槽"></a>2. 具名插槽</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs vue">父组件中：<br>        &lt;Category title=&quot;今日热门游戏&quot;&gt;<br>          &lt;template v-slot:s1&gt;<br>            &lt;ul&gt;<br>              &lt;li v-for=&quot;g in games&quot; :key=&quot;g.id&quot;&gt;&#123;&#123; g.name &#125;&#125;&lt;/li&gt;<br>            &lt;/ul&gt;<br>          &lt;/template&gt;<br>          &lt;template #s2&gt;<br>            &lt;a href=&quot;&quot;&gt;更多&lt;/a&gt;<br>          &lt;/template&gt;<br>        &lt;/Category&gt;<br>子组件中：<br>        &lt;template&gt;<br>          &lt;div class=&quot;item&quot;&gt;<br>            &lt;h3&gt;&#123;&#123; title &#125;&#125;&lt;/h3&gt;<br>            &lt;slot name=&quot;s1&quot;&gt;&lt;/slot&gt;<br>            &lt;slot name=&quot;s2&quot;&gt;&lt;/slot&gt;<br>          &lt;/div&gt;<br>        &lt;/template&gt;<br></code></pre></td></tr></table></figure>

<h3 id="3-作用域插槽"><a href="#3-作用域插槽" class="headerlink" title="3. 作用域插槽"></a>3. 作用域插槽</h3><ol>
<li><p>理解：<span style="color:red">数据在组件的自身，但根据数据生成的结构需要组件的使用者来决定。</span>（新闻数据在<code>News</code>组件中，但使用数据所遍历出来的结构由<code>App</code>组件决定）</p>
</li>
<li><p>具体编码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs vue">父组件中：<br>      &lt;Game v-slot=&quot;params&quot;&gt;<br>      &lt;!-- &lt;Game v-slot:default=&quot;params&quot;&gt; --&gt;<br>      &lt;!-- &lt;Game #default=&quot;params&quot;&gt; --&gt;<br>        &lt;ul&gt;<br>          &lt;li v-for=&quot;g in params.games&quot; :key=&quot;g.id&quot;&gt;&#123;&#123; g.name &#125;&#125;&lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/Game&gt;<br><br>子组件中：<br>      &lt;template&gt;<br>        &lt;div class=&quot;category&quot;&gt;<br>          &lt;h2&gt;今日游戏榜单&lt;/h2&gt;<br>          &lt;slot :games=&quot;games&quot; a=&quot;哈哈&quot;&gt;&lt;/slot&gt;<br>        &lt;/div&gt;<br>      &lt;/template&gt;<br><br>      &lt;script setup lang=&quot;ts&quot; name=&quot;Category&quot;&gt;<br>        import &#123;reactive&#125; from &#x27;vue&#x27;<br>        let games = reactive([<br>          &#123;id:&#x27;asgdytsa01&#x27;,name:&#x27;英雄联盟&#x27;&#125;,<br>          &#123;id:&#x27;asgdytsa02&#x27;,name:&#x27;王者荣耀&#x27;&#125;,<br>          &#123;id:&#x27;asgdytsa03&#x27;,name:&#x27;红色警戒&#x27;&#125;,<br>          &#123;id:&#x27;asgdytsa04&#x27;,name:&#x27;斗罗大陆&#x27;&#125;<br>        ])<br>      &lt;/script&gt;<br></code></pre></td></tr></table></figure></li>
</ol>
<h1 id="7-其它-API"><a href="#7-其它-API" class="headerlink" title="7. 其它 API"></a>7. 其它 API</h1><h2 id="7-1-【shallowRef-与-shallowReactive-】"><a href="#7-1-【shallowRef-与-shallowReactive-】" class="headerlink" title="7.1.【shallowRef 与 shallowReactive 】"></a>7.1.【shallowRef 与 shallowReactive 】</h2><h3 id="shallowRef"><a href="#shallowRef" class="headerlink" title="shallowRef"></a><code>shallowRef</code></h3><ol>
<li><p>作用：创建一个响应式数据，但只对顶层属性进行响应式处理。</p>
</li>
<li><p>用法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> myVar = <span class="hljs-title function_">shallowRef</span>(initialValue);<br></code></pre></td></tr></table></figure>
</li>
<li><p>特点：只跟踪引用值的变化，不关心值内部的属性变化。</p>
</li>
</ol>
<h3 id="shallowReactive"><a href="#shallowReactive" class="headerlink" title="shallowReactive"></a><code>shallowReactive</code></h3><ol>
<li><p>作用：创建一个浅层响应式对象，只会使对象的最顶层属性变成响应式的，对象内部的嵌套属性则不会变成响应式的</p>
</li>
<li><p>用法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> myObj = <span class="hljs-title function_">shallowReactive</span>(&#123; ... &#125;);<br></code></pre></td></tr></table></figure>
</li>
<li><p>特点：对象的顶层属性是响应式的，但嵌套对象的属性不是。</p>
</li>
</ol>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><blockquote>
<p>通过使用 <a target="_blank" rel="noopener" href="https://cn.vuejs.org/api/reactivity-advanced.html#shallowref"><code>shallowRef()</code></a> 和 <a target="_blank" rel="noopener" href="https://cn.vuejs.org/api/reactivity-advanced.html#shallowreactive"><code>shallowReactive()</code></a> 来绕开深度响应。浅层式 <code>API</code> 创建的状态只在其顶层是响应式的，对所有深层的对象不会做任何处理，避免了对每一个内部属性做响应式所带来的性能成本，这使得属性的访问变得更快，可提升性能。</p>
</blockquote>
<h2 id="7-2-【readonly-与-shallowReadonly】"><a href="#7-2-【readonly-与-shallowReadonly】" class="headerlink" title="7.2.【readonly 与 shallowReadonly】"></a>7.2.【readonly 与 shallowReadonly】</h2><h3 id="readonly"><a href="#readonly" class="headerlink" title="readonly"></a><strong><code>readonly</code></strong></h3><ol>
<li><p>作用：用于创建一个对象的深只读副本。</p>
</li>
<li><p>用法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> original = <span class="hljs-title function_">reactive</span>(&#123; ... &#125;);<br><span class="hljs-keyword">const</span> readOnlyCopy = <span class="hljs-title function_">readonly</span>(original);<br></code></pre></td></tr></table></figure>
</li>
<li><p>特点：</p>
<ul>
<li>对象的所有嵌套属性都将变为只读。</li>
<li>任何尝试修改这个对象的操作都会被阻止（在开发模式下，还会在控制台中发出警告）。</li>
</ul>
</li>
<li><p>应用场景：</p>
<ul>
<li>创建不可变的状态快照。</li>
<li>保护全局状态或配置不被修改。</li>
</ul>
</li>
</ol>
<h3 id="shallowReadonly"><a href="#shallowReadonly" class="headerlink" title="shallowReadonly"></a><strong><code>shallowReadonly</code></strong></h3><ol>
<li><p>作用：与 <code>readonly</code> 类似，但只作用于对象的顶层属性。</p>
</li>
<li><p>用法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> original = <span class="hljs-title function_">reactive</span>(&#123; ... &#125;);<br><span class="hljs-keyword">const</span> shallowReadOnlyCopy = <span class="hljs-title function_">shallowReadonly</span>(original);<br></code></pre></td></tr></table></figure>
</li>
<li><p>特点：</p>
<ul>
<li><p>只将对象的顶层属性设置为只读，对象内部的嵌套属性仍然是可变的。</p>
</li>
<li><p>适用于只需保护对象顶层属性的场景</p>
</li>
</ul>
</li>
</ol>
<h2 id="7-3-【toRaw-与-markRaw】"><a href="#7-3-【toRaw-与-markRaw】" class="headerlink" title="7.3.【toRaw 与 markRaw】"></a>7.3.【toRaw 与 markRaw】</h2><h3 id="toRaw"><a href="#toRaw" class="headerlink" title="toRaw"></a><code>toRaw</code></h3><ol>
<li><p>作用：用于获取一个响应式对象的原始对象， <code>toRaw</code> 返回的对象不再是响应式的，不会触发视图更新。</p>
<blockquote>
<p>官网描述：这是一个可以用于临时读取而不引起代理访问&#x2F;跟踪开销，或是写入而不触发更改的特殊方法。不建议保存对原始对象的持久引用，请谨慎使用。</p>
</blockquote>
<blockquote>
<p>何时使用？ —— 在需要将响应式对象传递给非 <code>Vue</code> 的库或外部系统时，使用 <code>toRaw</code> 可以确保它们收到的是普通对象</p>
</blockquote>
</li>
<li><p>具体编码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123; reactive,toRaw,markRaw,isReactive &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;vue&quot;</span>;<br><br><span class="hljs-comment">/* toRaw */</span><br><span class="hljs-comment">// 响应式对象</span><br><span class="hljs-keyword">let</span> person = <span class="hljs-title function_">reactive</span>(&#123;<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;tony&#x27;</span>,<span class="hljs-attr">age</span>:<span class="hljs-number">18</span>&#125;)<br><span class="hljs-comment">// 原始对象</span><br><span class="hljs-keyword">let</span> rawPerson = <span class="hljs-title function_">toRaw</span>(person)<br><br><br><span class="hljs-comment">/* markRaw */</span><br><span class="hljs-keyword">let</span> citysd = <span class="hljs-title function_">markRaw</span>([<br>  &#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;asdda01&#x27;</span>,<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;北京&#x27;</span>&#125;,<br>  &#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;asdda02&#x27;</span>,<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;上海&#x27;</span>&#125;,<br>  &#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;asdda03&#x27;</span>,<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;天津&#x27;</span>&#125;,<br>  &#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;asdda04&#x27;</span>,<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;重庆&#x27;</span>&#125;<br>])<br><span class="hljs-comment">// 根据原始对象citys去创建响应式对象citys2 —— 创建失败，因为citys被markRaw标记了</span><br><span class="hljs-keyword">let</span> citys2 = <span class="hljs-title function_">reactive</span>(citys)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">isReactive</span>(person))<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">isReactive</span>(rawPerson))<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">isReactive</span>(citys))<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">isReactive</span>(citys2))<br></code></pre></td></tr></table></figure></li>
</ol>
<h3 id="markRaw"><a href="#markRaw" class="headerlink" title="markRaw"></a><code>markRaw</code></h3><ol>
<li><p>作用：标记一个对象，使其<strong>永远不会</strong>变成响应式的。</p>
<blockquote>
<p>例如使用<code>mockjs</code>时，为了防止误把<code>mockjs</code>变为响应式对象，可以使用 <code>markRaw</code> 去标记<code>mockjs</code></p>
</blockquote>
</li>
<li><p>编码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">/* markRaw */</span><br><span class="hljs-keyword">let</span> citys = <span class="hljs-title function_">markRaw</span>([<br>  &#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;asdda01&#x27;</span>,<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;北京&#x27;</span>&#125;,<br>  &#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;asdda02&#x27;</span>,<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;上海&#x27;</span>&#125;,<br>  &#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;asdda03&#x27;</span>,<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;天津&#x27;</span>&#125;,<br>  &#123;<span class="hljs-attr">id</span>:<span class="hljs-string">&#x27;asdda04&#x27;</span>,<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;重庆&#x27;</span>&#125;<br>])<br><span class="hljs-comment">// 根据原始对象citys去创建响应式对象citys2 —— 创建失败，因为citys被markRaw标记了</span><br><span class="hljs-keyword">let</span> citys2 = <span class="hljs-title function_">reactive</span>(citys)<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="7-4-【customRef】"><a href="#7-4-【customRef】" class="headerlink" title="7.4.【customRef】"></a>7.4.【customRef】</h2><p>作用：创建一个自定义的<code>ref</code>，并对其依赖项跟踪和更新触发进行逻辑控制。</p>
<p>实现防抖效果（<code>useSumRef.ts</code>）：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">import</span> &#123;customRef &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;vue&quot;</span>;<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">function</span>(<span class="hljs-params">initValue:<span class="hljs-built_in">string</span>,delay:<span class="hljs-built_in">number</span></span>)&#123;<br>  <span class="hljs-keyword">let</span> msg = <span class="hljs-title function_">customRef</span>(<span class="hljs-function">(<span class="hljs-params">track,trigger</span>)=&gt;</span>&#123;<br>    <span class="hljs-keyword">let</span> <span class="hljs-attr">timer</span>:<span class="hljs-built_in">number</span><br>    <span class="hljs-keyword">return</span> &#123;<br>      <span class="hljs-title function_">get</span>(<span class="hljs-params"></span>)&#123;<br>        <span class="hljs-title function_">track</span>() <span class="hljs-comment">// 告诉Vue数据msg很重要，要对msg持续关注，一旦变化就更新</span><br>        <span class="hljs-keyword">return</span> initValue<br>      &#125;,<br>      <span class="hljs-title function_">set</span>(<span class="hljs-params">value</span>)&#123;<br>        <span class="hljs-built_in">clearTimeout</span>(timer)<br>        timer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> &#123;<br>          initValue = value<br>          <span class="hljs-title function_">trigger</span>() <span class="hljs-comment">//通知Vue数据msg变化了</span><br>        &#125;, delay);<br>      &#125;<br>    &#125;<br>  &#125;) <br>  <span class="hljs-keyword">return</span> &#123;msg&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>组件中使用：</p>
<h1 id="8-Vue3新组件"><a href="#8-Vue3新组件" class="headerlink" title="8. Vue3新组件"></a>8. Vue3新组件</h1><h2 id="8-1-【Teleport】"><a href="#8-1-【Teleport】" class="headerlink" title="8.1. 【Teleport】"></a>8.1. 【Teleport】</h2><ul>
<li>什么是Teleport？—— Teleport 是一种能够将我们的<strong>组件html结构</strong>移动到指定位置的技术。</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">teleport</span> <span class="hljs-attr">to</span>=<span class="hljs-string">&#x27;body&#x27;</span> &gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;modal&quot;</span> <span class="hljs-attr">v-show</span>=<span class="hljs-string">&quot;isShow&quot;</span>&gt;</span><br>      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>我是一个弹窗<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span><br>      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>我是弹窗中的一些内容<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span><br>      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">&quot;isShow = false&quot;</span>&gt;</span>关闭弹窗<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">teleport</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h2 id="8-2-【Suspense】"><a href="#8-2-【Suspense】" class="headerlink" title="8.2. 【Suspense】"></a>8.2. 【Suspense】</h2><ul>
<li>等待异步组件时渲染一些额外内容，让应用有更好的用户体验 </li>
<li>使用步骤： <ul>
<li>异步引入组件</li>
<li>使用<code>Suspense</code>包裹组件，并配置好<code>default</code> 与 <code>fallback</code></li>
</ul>
</li>
</ul>
<figure class="highlight tsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs tsx"><span class="hljs-keyword">import</span> &#123; defineAsyncComponent,<span class="hljs-title class_">Suspense</span> &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;vue&quot;</span>;<br><span class="hljs-keyword">const</span> <span class="hljs-title class_">Child</span> = <span class="hljs-title function_">defineAsyncComponent</span>(<span class="hljs-function">()=&gt;</span><span class="hljs-keyword">import</span>(<span class="hljs-string">&#x27;./Child.vue&#x27;</span>))<br></code></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>    &lt;div class=&quot;app&quot;&gt;<br>        &lt;h3&gt;我是App组件&lt;/h3&gt;<br>        &lt;Suspense&gt;<br>          &lt;template v-slot:default&gt;<br>            &lt;Child/&gt;<br>          &lt;/template&gt;<br>          &lt;template v-slot:fallback&gt;<br>            &lt;h3&gt;加载中.......&lt;/h3&gt;<br>          &lt;/template&gt;<br>        &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure>

<h2 id="8-3-【全局API转移到应用对象】"><a href="#8-3-【全局API转移到应用对象】" class="headerlink" title="8.3.【全局API转移到应用对象】"></a>8.3.【全局API转移到应用对象】</h2><ul>
<li><code>app.component</code></li>
<li><code>app.config</code></li>
<li><code>app.directive</code></li>
<li><code>app.mount</code></li>
<li><code>app.unmount</code></li>
<li><code>app.use</code></li>
</ul>
<h2 id="8-4-【其他】"><a href="#8-4-【其他】" class="headerlink" title="8.4.【其他】"></a>8.4.【其他】</h2><ul>
<li><p>过渡类名 <code>v-enter</code> 修改为 <code>v-enter-from</code>、过渡类名 <code>v-leave</code> 修改为 <code>v-leave-from</code>。</p>
</li>
<li><p><code>keyCode</code> 作为 <code>v-on</code> 修饰符的支持。</p>
</li>
<li><p><code>v-model</code> 指令在组件上的使用已经被重新设计，替换掉了 <code>v-bind.sync。</code></p>
</li>
<li><p><code>v-if</code> 和 <code>v-for</code> 在同一个元素身上使用时的优先级发生了变化。</p>
</li>
<li><p>移除了<code>$on</code>、<code>$off</code> 和 <code>$once</code> 实例方法。</p>
</li>
<li><p>移除了过滤器 <code>filter</code>。</p>
</li>
<li><p>移除了<code>$children</code> 实例 <code>propert</code>。</p>
<p>……</p>
</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/blog/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="print-no-link">#学习笔记</a>
      
        <a href="/blog/tags/vue/" class="print-no-link">#vue</a>
      
        <a href="/blog/tags/vue3/" class="print-no-link">#vue3</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Vue3学习笔记</div>
      <div>https://isolace.gitee.io/blog/2024/03/26/Vue3学习笔记/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Solace</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2024年3月26日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2024/03/26/%E8%93%9D%E6%A1%A5%E6%9D%AFweb%E7%BB%84%E8%80%83%E7%82%B9/" title="蓝桥杯web组考点">
                        <span class="hidden-mobile">蓝桥杯web组考点</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="twikoo"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#comments', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/twikoo/1.6.8/twikoo.all.min.js', function() {
        var options = Object.assign(
          {"envId":"https://imaginative-rabanadas-4bf3ac.netlify.app/.netlify/functions/twikoo","region":"AWS / N. Virginia (us-east-1)","path":"window.location.pathname"},
          {
            el: '#twikoo',
            path: 'window.location.pathname',
            onCommentLoaded: function() {
              Fluid.utils.listenDOMLoaded(function() {
                var imgSelector = '#twikoo .tk-content img:not(.tk-owo-emotion)';
                Fluid.plugins.imageCaption(imgSelector);
                Fluid.plugins.fancyBox(imgSelector);
              });
            }
          }
        )
        twikoo.init(options)
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  


  
  









    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>Solace</span><br> <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>





  
    <script  src="/blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  
      <script>
        if (!window.MathJax) {
          window.MathJax = {
            tex    : {
              inlineMath: { '[+]': [['$', '$']] }
            },
            loader : {
              load: ['ui/lazy']
            },
            options: {
              renderActions: {
                insertedScript: [200, () => {
                  document.querySelectorAll('mjx-container').forEach(node => {
                    let target = node.parentNode;
                    if (target.nodeName.toLowerCase() === 'li') {
                      target.parentNode.classList.add('has-jax');
                    }
                  });
                }, '', false]
              }
            }
          };
        } else {
          MathJax.startup.document.state(0);
          MathJax.texReset();
          MathJax.typeset();
          MathJax.typesetPromise();
        }

        Fluid.events.registerRefreshCallback(function() {
          if ('MathJax' in window && MathJax.startup.document && typeof MathJax.startup.document.state === 'function') {
            MathJax.startup.document.state(0);
            MathJax.texReset();
            MathJax.typeset();
            MathJax.typesetPromise();
          }
        });
      </script>
    

  <script  src="https://lib.baomitu.com/mathjax/3.2.2/es5/tex-mml-chtml.js" ></script>

  <script  src="/blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
